When i use nio serverSocket.accept () throws IllegalBlockingModeException

When I do the code like this:

ServerSocketChannel ssc = ServerSocketChannel.open();
InetSocketAddress sa = new InetSocketAddress("localhost",8888);
ssc.socket().bind(sa);
ssc.configureBlocking(false);
ssc.socket().accept();

      

method ServerSocket.accept()

throws out java.nio.channels.IllegalBlockingModeException

. Why can't I call accept()

even though I've set the lock to false

?

+1


source to share


3 answers


The Javadoc specifically states that ServerSocketChannel.accept()

:

Accepts a connection on this pipe socket.

If this channel is in non-blocking mode, then this method will immediately return null if there are no pending connections. Otherwise, it blocks indefinitely until a new connection is available or an I / O error occurs.

General idea:



  • If you want to block while waiting for incoming connections, you leave the server socket in blocking mode. If you are writing a server that has nothing to do until it actually connects, then blocking mode is what you want.
  • If you want to do other things and check periodically to see if there is a pending connection, you want non-blocking mode.

Default blocking mode: Most servers do not want to poll their receiving socket for incoming connections.

+2


source


Because what the javadoc for serversocket.accept () says?



IllegalBlockingModeException - if this socket has an associated pipe and the pipe is in non-blocking mode.

+1


source


The problem is that you are calling ssc.socket().accept()

, not ssc.accept()

. If you change the last line to ssc.accept()

, then it works as expected, which is what SocketChannel should return if you expect it, or null if not.

+1


source







All Articles