Waiting for ServerSocket accept() to put socket into "listen" mode

inazaruk picture inazaruk · Dec 29, 2010 · Viewed 7.2k times · Source

I need a simple client-server communication in order to implement unit-test.

My steps:

  1. Create server thread
  2. Wait for server thread to put server socket into listen mode ( serverSocket.accept() )
  3. Create client
  4. Make some request, verify responses

Basically, I have a problem with step #2. I can't find a way to signal me when server socket is put to "listen" state. An asynchronous call to "accept" will do in this case, but java doesn't support this (it seems to support only asynchronous channels and those are incompatible with "accept()" method according to documentation).

Of cause I can put a simple "sleep", but that is not really a solution for production code.

So, to summarize, I need to detect when ServerSocket has been put into listen mode without using sleeps and/or polling.

Answer

Joe Daley picture Joe Daley · Dec 29, 2010

The socket is put into listening state as soon as you construct the ServerSocket object, not when you call accept. As long as you create the client after the ServerSocket constructor has completed, you won't have a problem. Connections will be accepted and internally queued until accept gets called.

Here is some code to demonstrate:

ServerSocket serverSocket = new ServerSocket(12345);
Thread.sleep(10000);
Socket socket = serverSocket.accept();

During that 10 second gap before accept is called, the OS netstat command will show the server socket in "LISTENING" state, and clients can connect to it. If a client connects during that 10 seconds, the connection is queued, and when the accept method is finally called it immediately returns the queued Socket object.