I’m using a SocketChannel with a network socket, and have to handle the expected exception of the other end of the socket closing the channel unexpectedly.
The problem is, I get this IOException:
java.io.IOException: An existing connection was forcibly closed by the remote host
at sun.nio.ch.SocketDispatcher.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(Unknown Source)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source)
at sun.nio.ch.IOUtil.read(Unknown Source)
at sun.nio.ch.SocketChannelImpl.read(Unknown Source)
...
I need to distinguish between this exception, which is expected to happen, and unexpected exceptions, so that I can log/print the unexpected ones and handle this one. But it’s just an ordinary IOException with a different text message, and although I always check SocketChannel.isOpen() and SocketChannel.isConnected(), they seem to return true in this case even though the other end of the socket has been closed.
What can/should I do?
the isOpen() and isConnected() should be more accurately called hasBeenOpenned() and hasBeenConnected(). Once they are true, they do not return to false.
You may have to do a e.getMessage().contains(“closed by the remote host”). Unfortunately, this is likely to be a platform dependant.
Instead I suggest you allow the protocol to send a “Closed” message of some kind and treat any exception without this first as unexpected.