Close ServerSocket Listening

In my Server application, I am trying to process a server that uses ServerSocket, for example,

  • Start the server and wait for the connection.
  • Stop the server connected to the client.
  • Stop the server waiting for the client.

I can start the server and make it wait for the client inside the thread using

socket = serverSocket.accept();

What I want to do is that I want to manually close the socket that is waiting for the connection, I tried to use,

if (thread != null) {
     thread.stop();
     thread = null;
  }
  if (socket != null) {
     try {
        socket.close();
        socket = null;
     }
     catch (IOException e) {
        e.printStackTrace();
     }
  }

After executing the above code, even if the socket becomes null when I try to connect from the client to the server, the connection is established, so my question is how to interrupt the servers that listen on the connection here,

socket = serverSocket.accept();
+3
source share
2 answers

ServerSocket, SocketClosedException.

thread.stop(). . Javadoc.

+2

, , accept() .

- :

ServerSocket server = new ServerSocket();
server.setSoTimeout(1000); // 1 second, could change to whatever you like

while (running) { // running would be a member variable
     try {
         server.accept(); // handle the connection here
     }
     catch (SocketTimeoutException e) {
          // You don't really need to handle this
     }
}

, , "running" false .

, !

+4

All Articles