views:

71

answers:

4

What's the best way to implement a non-blocking socket in Java? Or is there such thing? I have a program that communicates with a server through socket but I don't want the socket call to block/cause delay if there is a problem with the data/connection.

A: 

Have a look at Java NIO.

duffymo
A: 

java.nio package provides Selector working much like as in C.

secmask
A: 

Apart from using non blocking IO, you might find it is much simpler to have a writing thread for your connection.

Peter Lawrey
+1  A: 

Several of these answers are incorrect. SocketChannel.configureBlocking(false) puts it into non-blocking mode. You don't need a Selector to do that. You only need a Selector to implement timeouts or multiplexed I/O with non-blocking sockets.

EJP