user41940
user41940

Reputation: 49

when I use nio, serverSocket.accept() throws IllegalBlockingModeException

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

Answers (3)

Nick H
Nick H

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

Brian Clapper
Brian Clapper

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:

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

Blocking mode is the default for a reason: Most servers don't want to poll their accepting socket for incoming connections.

Upvotes: 2

Yoni Roit
Yoni Roit

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

Related Questions