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
?
source to share
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.
source to share