This is a pretty basic question, but I can't find a definitive answer for it anywhere:
When I accept() a connection from a ServerSocketChannel, am I guaranteed that the returned SocketChannel is "connected", or could it happen that the returned channel is still performing some form a handshake or whatever and will only later set its SelectionKey.OP_CONNECT
bit?
In other words, am I guaranteed that the following piece of code will never print false
?
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(1234));
SocketChannel socketChannel = serverSocketChannel.accept();
System.out.println(socketChannel.isConnected());
According to the source of ServerSocketChannelImpl
the ServerSocketChannelImpl
creates a SocketChannelImpl
with a state of ST_CONNECTED.
Since the SocketChannelImpl.isConnected()
method checks for a state of ST_CONNECTED, your test should always return true.
That is however the scenario for the good times. What could happen is that your server thread gets delayed and by the time your thread calls isConnected()
the client already closed the connection.
So, no, there is no guarantee that your code will never print false.