Java Code Examples for java.net.ServerSocket#isClosed()

The following examples show how to use java.net.ServerSocket#isClosed() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EchoServer.java    From jgroups-docker with Apache License 2.0 6 votes vote down vote up
protected void start(InetAddress bind_addr, int port) throws Exception {
    srv_sock=new ServerSocket(port, 50, bind_addr);
    System.out.printf("%s listening on %s\n", EchoServer.class.getSimpleName(), srv_sock.getLocalSocketAddress());
    while(!srv_sock.isClosed()) {
        try {
            Socket client_sock=srv_sock.accept();
            ConnectionHandler handler=new ConnectionHandler(client_sock);
            thread_pool.execute(handler);
        }
        catch(Throwable t) {
            t.printStackTrace();
        }
    }
    thread_pool.shutdown();
    thread_pool.awaitTermination(3, TimeUnit.SECONDS);
}
 
Example 2
Source File: GraphiteMockServer.java    From elasticsearch-graphite-plugin with Do What The F*ck You Want To Public License 6 votes vote down vote up
@Override
public void run() {
    try {
        server = new ServerSocket(port);
        Socket client;

        while (!isClosed) {
            if (server.isClosed()) return;

            client = server.accept();

            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

            String msg;
            while ((msg = in.readLine()) != null) {
                content.add(msg.trim());
            }
        }

    } catch (IOException e) {
        if (!(e instanceof SocketException)) {
            e.printStackTrace();
        }
    }
}
 
Example 3
Source File: Socks5Proxy.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (true) {
        ServerSocket serverSocket = Socks5Proxy.this.serverSocket;
        if (serverSocket == null || serverSocket.isClosed() || Thread.currentThread().isInterrupted()) {
            return;
        }

        // accept connection
        Socket socket = null;
        try {
            socket = serverSocket.accept();
            // initialize connection
            establishConnection(socket);
        } catch (SmackException | IOException e) {
            // Do nothing, if caused by closing the server socket, thread will terminate in next loop.
            LOGGER.log(Level.FINE, "Exception while " + Socks5Proxy.this + " was handling connection", e);
            CloseableUtil.maybeClose(socket, LOGGER);
        }
    }
}
 
Example 4
Source File: SocketUtils.java    From 30-android-libraries-in-30-days with Apache License 2.0 5 votes vote down vote up
public static final void closeSocket(final ServerSocket pServerSocket) {
	if(pServerSocket != null && !pServerSocket.isClosed()) {
		try {
			pServerSocket.close();
		} catch (final IOException e) {
			Debug.e(e);
		}
	}
}
 
Example 5
Source File: JSSESocketFactory.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that the certificate is compatible with the enabled cipher suites.
 * If we don't check now, the JIoEndpoint can enter a nasty logging loop.
 * See bug 45528.
 */
private void checkConfig() throws IOException {
    // Create an unbound server socket
    ServerSocket socket = sslProxy.createServerSocket();
    initServerSocket(socket);

    try {
        // Set the timeout to 1ms as all we care about is if it throws an
        // SSLException on accept.
        socket.setSoTimeout(1);

        socket.accept();
        // Will never get here - no client can connect to an unbound port
    } catch (SSLException ssle) {
        // SSL configuration is invalid. Possibly cert doesn't match ciphers
        IOException ioe = new IOException(sm.getString(
                "jsse.invalid_ssl_conf", ssle.getMessage()));
        ioe.initCause(ssle);
        throw ioe;
    } catch (Exception e) {
        /*
         * Possible ways of getting here
         * socket.accept() throws a SecurityException
         * socket.setSoTimeout() throws a SocketException
         * socket.accept() throws some other exception (after a JDK change)
         *      In these cases the test won't work so carry on - essentially
         *      the behaviour before this patch
         * socket.accept() throws a SocketTimeoutException
         *      In this case all is well so carry on
         */
    } finally {
        // Should be open here but just in case
        if (!socket.isClosed()) {
            socket.close();
        }
    }

}
 
Example 6
Source File: JSSESocketFactory.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that the certificate is compatible with the enabled cipher suites.
 * If we don't check now, the JIoEndpoint can enter a nasty logging loop.
 * See bug 45528.
 */
private void checkConfig() throws IOException {
    // Create an unbound server socket
    ServerSocket socket = sslProxy.createServerSocket();
    initServerSocket(socket);

    try {
        // Set the timeout to 1ms as all we care about is if it throws an
        // SSLException on accept.
        socket.setSoTimeout(1);

        socket.accept();
        // Will never get here - no client can connect to an unbound port
    } catch (SSLException ssle) {
        // SSL configuration is invalid. Possibly cert doesn't match ciphers
        IOException ioe = new IOException(sm.getString(
                "jsse.invalid_ssl_conf", ssle.getMessage()));
        ioe.initCause(ssle);
        throw ioe;
    } catch (Exception e) {
        /*
         * Possible ways of getting here
         * socket.accept() throws a SecurityException
         * socket.setSoTimeout() throws a SocketException
         * socket.accept() throws some other exception (after a JDK change)
         *      In these cases the test won't work so carry on - essentially
         *      the behaviour before this patch
         * socket.accept() throws a SocketTimeoutException
         *      In this case all is well so carry on
         */
    } finally {
        // Should be open here but just in case
        if (!socket.isClosed()) {
            socket.close();
        }
    }

}
 
Example 7
Source File: SocketChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Regression test for Harmony-1947.
 */
public void test_finishConnect() throws Exception {
    SocketAddress address = new InetSocketAddress("localhost", 0);

    ServerSocketChannel theServerChannel = ServerSocketChannel.open();
    ServerSocket serversocket = theServerChannel.socket();
    serversocket.setReuseAddress(true);
    // Bind the socket
    theServerChannel.socket().bind(address);

    boolean doneNonBlockingConnect = false;
    // Loop so that we make sure we're definitely testing finishConnect()
    while (!doneNonBlockingConnect) {
        channel1 = SocketChannel.open();

        // Set the SocketChannel to non-blocking so that connect(..) does
        // not block
        channel1.configureBlocking(false);
        boolean connected = channel1.connect(new InetSocketAddress("localhost",serversocket.getLocalPort()));
        if (!connected) {
            // Now set the SocketChannel back to blocking so that
            // finishConnect() blocks.
            channel1.configureBlocking(true);
            doneNonBlockingConnect = channel1.finishConnect();
        }
        if (doneNonBlockingConnect) {
            tryFinish();
        }
        channel1.close();
    }
    if (!serversocket.isClosed()) {
        serversocket.close();
    }
}
 
Example 8
Source File: SocketServerRpcConnectionFactory.java    From protobuf-socket-rpc with MIT License 5 votes vote down vote up
@Override
public void close() throws IOException {
  ServerSocket local = serverSocket;
  if (local != null && !local.isClosed()) {
    local.close();
  }
}
 
Example 9
Source File: TcpSocketProxy.java    From mesos-rxjava with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    LOGGER.debug("Proxy shutdown starting...");
    shutdown.set(true);
    try {
        if (!service.isShutdown()) {
            service.shutdown();
        }
        for (Future<?> f : futures) {
            f.cancel(true);
        }
        final ServerSocket serverSocket = socketRef.get();
        if (!serverSocket.isClosed()) {
            serverSocket.close();
        }
        for (Socket socket : sockets) {
            try {
                socket.close();
            } catch (IOException ignored) {
                // if we get an exception trying to close one socket swallow it and move onto the next one
            }
        }
        LOGGER.debug("Proxy shutdown complete");
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        shutdownCountDownLatch.countDown();
    }
}
 
Example 10
Source File: ReadTimeoutAcceptanceTest.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
private void close(final ServerSocket socket) {
  try {
    if (!socket.isClosed()) {
      socket.close();
    }
  } catch (final IOException e) {
    LOG.warn("Problem closing unresponsive socket {}", socket.getInetAddress(), e);
  }
}
 
Example 11
Source File: NanoHTTPD.java    From LiveMultimedia with Apache License 2.0 4 votes vote down vote up
/**
 * Start the server.
 *
 * @throws IOException if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    asyncRunner.exec(new Runnable() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            try {
                                outputStream = finalAccept.getOutputStream();
                                TempFileManager tempFileManager = tempFileManagerFactory.create();
                                HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress());
                                while (!finalAccept.isClosed()) {
                                    session.execute();
                                }
                            } catch (Exception e) {
                                // When the socket is closed by the client, we throw our own SocketException
                                // to break the  "keep alive" loop above.
                                if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                    e.printStackTrace();
                                }
                            } finally {
                                safeClose(outputStream);
                                safeClose(inputStream);
                                safeClose(finalAccept);
                                unRegisterConnection(finalAccept);
                            }
                        }
                    });
                } catch (IOException e) {
                   Log.e(TAG, e.getMessage());
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}
 
Example 12
Source File: NanoHTTPD.java    From jmeter-plugins with Apache License 2.0 4 votes vote down vote up
/**
 * Start the server.
 *
 * @throws IOException
 *             if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket.bind((hostname != null) ? new InetSocketAddress(
            hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept
                            .getInputStream();
                    asyncRunner.exec(new Runnable() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            try {
                                outputStream = finalAccept
                                        .getOutputStream();
                                TempFileManager tempFileManager = tempFileManagerFactory
                                        .create();
                                HTTPSession session = new HTTPSession(
                                        tempFileManager, inputStream,
                                        outputStream, finalAccept
                                                .getInetAddress());
                                while (!finalAccept.isClosed()) {
                                    session.execute();
                                }
                            } catch (Exception e) {
                                // When the socket is closed by the client,
                                // we throw our own SocketException
                                // to break the "keep alive" loop above.
                                if (!(e instanceof SocketException && "NanoHttpd Shutdown"
                                        .equals(e.getMessage()))) {
                                    e.printStackTrace();
                                }
                            } finally {
                                safeClose(outputStream);
                                safeClose(inputStream);
                                safeClose(finalAccept);
                                unRegisterConnection(finalAccept);
                            }
                        }
                    });
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}
 
Example 13
Source File: UsbServer.java    From slide-android with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void run()
{
    this.running = true;
    try
    {
        server = new ServerSocket(getPort());
        server.setReuseAddress(true);
        if (!server.isBound())
        {
            server.bind(new InetSocketAddress(getPort()));
        }

        if (!server.isClosed())
        {
            client = server.accept();
            client.setTcpNoDelay(true);

            output = new ObjectOutputStream(client.getOutputStream());
            output.flush();
        }
    } catch (IOException e)
    {
        e.printStackTrace();
    }

    //connected
    if (client != null)
    {
        final short sensitivity = AppSettings.getInstance().getSystemSettings().getMouseSensitivity();

        if (AppSettings.getInstance().getSettingsElements().getPositioningMode() == PositioningMode.ABSOLUTE)
        {
            AppSettings.getInstance().getConnectionManager()
                .getUsbConnectionManager()
                .send(PositioningMode.ABSOLUTE, sensitivity);
        } else
        {
            AppSettings.getInstance().getConnectionManager().getUsbConnectionManager().send(
                PositioningMode.RELATIVE, sensitivity);
        }

        SettingsActivity.getActivity().startActivity(
            AppSettings.getInstance().getActivitySettings()
                .getCanvasIntent()); // Load the Canvas
    }
}
 
Example 14
Source File: NanoHTTPD.java    From SB_Elsinore_Server with MIT License 4 votes vote down vote up
/**
 * Start the server.
 *
 * @throws IOException if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    if (inputStream == null) {
                        safeClose(finalAccept);
                        unRegisterConnection(finalAccept);
                    } else {
                        asyncRunner.exec(new Runnable() {
                            @Override
                            public void run() {
                                OutputStream outputStream = null;
                                try {
                                    outputStream = finalAccept.getOutputStream();
                                    TempFileManager tempFileManager = tempFileManagerFactory.create();
                                    HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress());
                                    while (!finalAccept.isClosed()) {
                                        session.execute();
                                    }
                                } catch (Exception e) {
                                    // When the socket is closed by the client, we throw our own SocketException
                                    // to break the  "keep alive" loop above.
                                    if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                        e.printStackTrace();
                                    }
                                } finally {
                                    safeClose(outputStream);
                                    safeClose(inputStream);
                                    safeClose(finalAccept);
                                    unRegisterConnection(finalAccept);
                                }
                            }
                        });
                    }
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}
 
Example 15
Source File: TcpDiscoveryWithWrongServerTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Stops tcp test thread
 * @throws IOException IOException
 */
private void stopTcpThreads() throws IOException {
    for (ServerSocket srvSock: srvSocks)
        if (!srvSock.isClosed())
            srvSock.close();
}
 
Example 16
Source File: NanoHTTPD.java    From LiveQAServerDemo with MIT License 4 votes vote down vote up
/**
 * Start the server.
 *
 * @throws IOException if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    asyncRunner.exec(new Runnable() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            try {
                                outputStream = finalAccept.getOutputStream();
                                TempFileManager tempFileManager = tempFileManagerFactory.create();
                                HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress());
                                while (!finalAccept.isClosed()) {
                                    session.execute();
                                }
                            } catch (Exception e) {
                                // When the socket is closed by the client, we throw our own SocketException
                                // to break the  "keep alive" loop above.
                                if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                    e.printStackTrace();
                                }
                            } finally {
                                safeClose(outputStream);
                                safeClose(inputStream);
                                safeClose(finalAccept);
                                unRegisterConnection(finalAccept);
                            }
                        }
                    });
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}
 
Example 17
Source File: NanoHTTPD.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
/**
 * Start the server.
 *
 * @throws IOException if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    asyncRunner.exec(new Runnable() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            try {
                                outputStream = finalAccept.getOutputStream();
                                TempFileManager tempFileManager = tempFileManagerFactory.create();
                                HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress());
                                while (!finalAccept.isClosed()) {
                                    session.execute();
                                }
                            } catch (Exception e) {
                                // When the socket is closed by the client, we throw our own SocketException
                                // to break the  "keep alive" loop above.
                                if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                    e.printStackTrace();
                                }
                            } finally {
                                safeClose(outputStream);
                                safeClose(inputStream);
                                safeClose(finalAccept);
                                unRegisterConnection(finalAccept);
                            }
                        }
                    });
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}
 
Example 18
Source File: NanoHTTPD.java    From BookReader with Apache License 2.0 4 votes vote down vote up
/**
 * Starts the server
 * <p/>
 * Throws an IOException if the socket is already in use
 */
public void start() throws IOException {
    Log.i("NanoHTTPD", "server start");
    myServerSocket = new ServerSocket();
    myServerSocket.bind((hostname != null) ? new InetSocketAddress(
            hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    Log.i("NanoHTTPD",
                            "accept request from "
                                    + finalAccept.getInetAddress());
                    InputStream inputStream = finalAccept.getInputStream();
                    OutputStream outputStream = finalAccept
                            .getOutputStream();
                    TempFileManager tempFileManager = tempFileManagerFactory
                            .create();
                    final HTTPSession session = new HTTPSession(
                            tempFileManager, inputStream, outputStream);
                    asyncRunner.exec(new Runnable() {
                        @Override
                        public void run() {
                            session.run();
                            if (finalAccept != null) {
                                try {
                                    finalAccept.close();
                                } catch (IOException ignored) {
                                }
                            }
                        }
                    });
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}
 
Example 19
Source File: NanoHTTPD.java    From fangzhuishushenqi with Apache License 2.0 4 votes vote down vote up
/**
 * Starts the server
 * <p/>
 * Throws an IOException if the socket is already in use
 */
public void start() throws IOException {
    Log.i("NanoHTTPD", "server start");
    myServerSocket = new ServerSocket();
    myServerSocket.bind((hostname != null) ? new InetSocketAddress(
            hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    Log.i("NanoHTTPD",
                            "accept request from "
                                    + finalAccept.getInetAddress());
                    InputStream inputStream = finalAccept.getInputStream();
                    OutputStream outputStream = finalAccept
                            .getOutputStream();
                    TempFileManager tempFileManager = tempFileManagerFactory
                            .create();
                    final HTTPSession session = new HTTPSession(
                            tempFileManager, inputStream, outputStream);
                    asyncRunner.exec(new Runnable() {
                        @Override
                        public void run() {
                            session.run();
                            if (finalAccept != null) {
                                try {
                                    finalAccept.close();
                                } catch (IOException ignored) {
                                }
                            }
                        }
                    });
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}
 
Example 20
Source File: LiMeServerController.java    From LiMe with MIT License 4 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
    String user = serverFrame.getHighlightedLime();
    String time = getLiMeTime();
    try {
        switch (e.getActionCommand()) {
            case SERVER_ACTION_START:
                // START Server
                cachedThreadPool = Executors.newCachedThreadPool();
                cachedThreadPool.execute(serverModel);
                break;
            case SERVER_ACTION_STOP:
                // STOP Server
                ServerSocket serverSocket = serverModel.getServerSocket();
                if (serverSocket != null && !serverSocket.isClosed()) {
                    serverSocket.close();
                }
                cachedThreadPool.shutdownNow();
                break;
            case SERVER_ACTION_KICK:
                serverModel.sendSeedStatus(user, ERROR_ADMIN_KICKED);
                // log UI
                serverFrame.appendLog("[" + time + "]\n< " + user + " > is KICKED.\n");
                break;
            case SERVER_ACTION_BAN:
                serverModel.sendSeedStatus(user, ERROR_ADMIN_BANNED);
                // Ban User in database
                serverModel.ban(user);
                // log UI
                serverFrame.appendLog("[" + time + "]\n< " + user + " > is BANNED.\n");
                break;
            case SERVER_ACTION_CLEAR_LOG:
                serverFrame.clearLog();
                break;
            case SERVER_ACTION_CLEAR_HISTORY:
                serverFrame.clearHistory();
                break;
            default:
                limeInternalError(this.getClass().getCanonicalName(), e.getActionCommand());
                break;
        }
    } catch (IOException | SQLException ex) {
        ex.printStackTrace();
        limeInternalError(this.getClass().getCanonicalName(), ex.getMessage());
    }
}