Search code examples
javasocketsselectorniochannel

Java nio SocketChannel failed to create


I've got this:

Selector selector = Selector.open();
ServerSocketChannel listenChannel = ServerSocketChannel.open();
listenChannel.socket().bind(new InetSocketAddress(12112));
listenChannel.register(selector, SelectionKey.OP_ACCEPT);

Just 4 lines of code inside main(), and the last line throws out exception:

java.nio.channels.IllegalBlockingModeException
at java.nio.channels.spi.AbstractSelectableChannel.register(AbstractSelectableChannel.java:201)
at java.nio.channels.SelectableChannel.register(SelectableChannel.java:280)
at myServer.main(myServer.java:18)

I just wish to create a ServerSocketChannel and register it to a Selector. What's wrong here, how to fix?

Thanks.


Solution

  • try turning off the blocking mode by:
    listenChannel.configureBlocking(false);