lukeo05 lukeo05 - 2 years ago 110
Java Question

How can I interrupt a ServerSocket accept() method?

In my main thread I have a

loop which calls
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
call in the
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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download