tags:

views:

629

answers:

3

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?

+1  A: 

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.

Yoni Roit
thanks for your help :)
+2  A: 

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.

Brian Clapper
+1  A: 

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.

Nick