Search code examples
javaserverniononblocking

Non Blocking ServerSocketChannel


SocketChannel socketChannel = serverSocketChannel.accept();

When a Non-Blocking ServerSocketChannel returns a SocketChannel, after calling socketChannel.configureBlocking(false), is it required to then register the SocketChannel using socketChannel.register(selector,SelectionKey.OP_CONNECT,new ConnectionHandler)?

I would assume that once the new SocketChannel has been returned that it is already connected to the remote endpoint and socketChannel.isConnectionPending() will return false and socketChannel.isConnected() will return true.

public class ConnectionHandler
{
  public void handleConnect ( SelectionKey key )
  {
    SocketChannel socketChannel = SocketChannel.class.cast ( key.channel() );
    socketChannel.finishConnect ();

    socketChannel.register ( key.selector (), SelectionKey.OP_READ );
  }
}

Solution

  • When a Non-Blocking ServerSocketChannel returns a SocketChannel, after calling socketChannel.configureBlocking(false), is it required to then register the SocketChannel using socketChannel.register(selector,SelectionKey.OP_CONNECT,new ConnectionHandler)?

    No. It's already connected. OP_CONNECT is for clients.

    I would assume that once the new SocketChannel has been returned that it is already connected to the remote endpoint and socketChannel.isConnectionPending() will return false and socketChannel.isConnected() will return true.

    Correct.