Reputation: 49
When I code like this:
ServerSocketChannel ssc = ServerSocketChannel.open();
InetSocketAddress sa = new InetSocketAddress("localhost",8888);
ssc.socket().bind(sa);
ssc.configureBlocking(false);
ssc.socket().accept();
the ServerSocket.accept()
method throws java.nio.channels.IllegalBlockingModeException
. Why can't I call accept()
, even though I set blocking to false
?
Upvotes: 1
Views: 2904
Reputation: 11535
The problem is that you are calling ssc.socket().accept()
, not ssc.accept()
. If you change the last line to ssc.accept()
then it will work as expected, which is to return a SocketChannel if one is waiting or null if not.
Upvotes: 3
Reputation: 26211
The Javadoc specifically states that ServerSocketChannel.accept()
:
Accepts a connection made to this channel's socket.
If this channel is in non-blocking mode then this method will immediately return null if there are no pending connections. Otherwise it will block indefinitely until a new connection is available or an I/O error occurs.
The general idea is:
Blocking mode is the default for a reason: Most servers don't want to poll their accepting socket for incoming connections.
Upvotes: 2
Reputation: 28686
Because that's what javadoc for serversocket.accept() says?
IllegalBlockingModeException - if this socket has an associated channel, and the channel is in non-blocking mode.
Upvotes: 2