Search code examples
javasocketsnio

Java NIO SocketChannel isOpen and isConnected methods


I am very new on NIO socket level programming and need help here. My application is based on NIO socket where it uses the Selectors for non blocking channel.

Wanted to know in which scenarios isOpen() and isConnected() methods of SocketChannel can return false.

As before writing data to the socket we are checking the above two methods. and seeing intermittently these methods are returning false.


Solution

  • isOpen() returns true until you close it.

    isConnected() returns true if you have connected or accepted the channel.

    Testing these continuously indicates that you don't understand what they are for. The application should already know the state into which it has put its own connections. Possibly you think they indicate the state of the connection, and that they change when the peer disconnects. They don't.

    As before writing data to the socket we are checking the above two methods. and seeing intermittently these methods are returning false.

    I doubt it. If you're seeing that, you have bugs in your code.