3

In my Server application I'm trying to handle the Server which is using ServerSocket like,

  1. Start the server and wait for connection.
  2. Stop the server which is connected with a client.
  3. Stop the server which is waiting for a client.

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

socket = serverSocket.accept();

What I want to do is I want manually close the socket which is waiting for connection, I have tried using,

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 though the socket becomes null, when I try to connect from client to server, the connection gets established, so my question is how to interrupt the serversocket which listening for connection over here,

socket = serverSocket.accept();
Vignesh
  • 3,571
  • 6
  • 28
  • 44

2 Answers2

5

I think a common way of handling this is make the accept() call time out in a loop.

So something like:

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
     }
}

Then, when you wanted to shut down your server, just have your code set 'running' to false and it will shut down.

I hope this makes sense!

  • Hi Phill Sacre, actually I dont't want to fix a time limit I want user to take control of starting and stopping the whenever He/She wants no matter it is listening or connected to a client, is it possible. – Vignesh May 25 '11 at 07:55
  • Hi Phill Sacre, I tried your suggestion, I fixed 60000 ms after 1 minute I'm getting SocketTimeoutException but still after that client can connect with server at particular socket, any idea? – Vignesh May 25 '11 at 10:05
  • @Vignesh because you haven't closed the ServerSocket. – user207421 Aug 29 '11 at 08:14
  • As EJP suggests, this is not a solution unless the serverSocket is closed. – Marco May 19 '16 at 05:47
2

Just close the ServerSocket, and catch the resulting SocketClosedException.

And get rid of the thread.stop(). For why, see the Javadoc.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
user207421
  • 305,947
  • 44
  • 307
  • 483