views:

248

answers:

4

Hi,

In my main thread I have a while(listening) loop which calls accept() on my ServerSocket object, then starts a new client thread and adds it to a Collection when a new client is accepted.

I also have an Admin thread which I want to use to issue commands, like 'exit', which will cause all the client threads to be shut down, shut itself down, and shut down the main thread, by turning listening to false.

However, the accept() call in the while(listening) loop blocks, and there doesn't seem to be any way to interrupt it, so the while condition cannot be checked again and the program cannot exit!

Is there a better way to do this? Or some way to interrupt the blocking method?

Thanks!

+1  A: 

Is calling close() on the ServerSocket an option?

http://java.sun.com/j2se/1.4.2/docs/api/java/net/ServerSocket.html#close%28%29

Closes this socket. Any thread currently blocked in accept() will throw a SocketException.

Lauri Lehtinen
+2  A: 

You can call close(), and the accept() call will throw a SocketException.

Simon Groenewolt
Thanks, so obvious, didn't even occur to me! I was calling close() after I exited the loop.
lukeo05
+1  A: 

Set timeout on accept(), then the call will timeout the blocking after specified time:

http://java.sun.com/j2se/1.4.2/docs/api/java/net/SocketOptions.html#SO_TIMEOUT

Set a timeout on blocking Socket operations: ServerSocket.accept(); SocketInputStream.read(); DatagramSocket.receive();

The option must be set prior to entering a blocking operation to take effect. If the timeout expires and the operation would continue to block, java.io.InterruptedIOException is raised. The Socket is not closed in this case.

Juha Syrjälä