Allow detaching the client from its connection.
[jFCPlib.git] / src / main / java / net / pterodactylus / fcp / highlevel / FcpClient.java
index 7399818..78cb198 100644 (file)
@@ -92,6 +92,9 @@ public class FcpClient {
        /** Whether the client is currently connected. */
        private volatile boolean connected;
 
+       /** The listener for “connection closed” events. */
+       private FcpListener connectionClosedListener;
+
        /**
         * Creates an FCP client with the given name.
         *
@@ -147,8 +150,33 @@ public class FcpClient {
         *            The Freenet node’s FCP port
         */
        public FcpClient(InetAddress host, int port) {
-               fcpConnection = new FcpConnection(host, port);
-               fcpConnection.addFcpListener(new FcpAdapter() {
+               this(new FcpConnection(host, port));
+       }
+
+       /**
+        * Creates a new high-level FCP client that will use the given connection.
+        * This constructor will assume that the FCP connection is already
+        * connected.
+        *
+        * @param fcpConnection
+        *            The FCP connection to use
+        */
+       public FcpClient(FcpConnection fcpConnection) {
+               this(fcpConnection, true);
+       }
+
+       /**
+        * Creates a new high-level FCP client that will use the given connection.
+        *
+        * @param fcpConnection
+        *            The FCP connection to use
+        * @param connected
+        *            The initial status of the FCP connection
+        */
+       public FcpClient(FcpConnection fcpConnection, boolean connected) {
+               this.fcpConnection = fcpConnection;
+               this.connected = connected;
+               connectionClosedListener = new FcpAdapter() {
 
                        /**
                         * {@inheritDoc}
@@ -156,10 +184,11 @@ public class FcpClient {
                        @Override
                        @SuppressWarnings("synthetic-access")
                        public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
-                               connected = false;
+                               FcpClient.this.connected = false;
                                fcpClientListenerManager.fireFcpClientDisconnected();
                        }
-               });
+               };
+               fcpConnection.addFcpListener(connectionClosedListener);
        }
 
        //
@@ -293,6 +322,13 @@ public class FcpClient {
                return connected;
        }
 
+       /**
+        * Detaches this client from its underlying FCP connection.
+        */
+       public void detach() {
+               fcpConnection.removeFcpListener(connectionClosedListener);
+       }
+
        //
        // PEER MANAGEMENT
        //