Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Why not to send single just before calling accept()?

connectionAccepted = true;
loc.notify();
socket.accept();

To be sure that the socket is ready add a tiny sleep in your "client" code:

wait();
// we are here when notify is called.
Thread.sleep(10); // 10 ms
startTest();

You can even do better: create loop that tries to "ping" the socket with a tiny sleep between attempts. In this case you will start test as quickly as it is possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top