Search code examples
javanio

How to detect a connection error on an NIO Channel


I have a situation where I have multiple connections to a number of servers and I wish to use NIO for this.

The Selector will tell me when there is data to read. Is there any way to know when a connection is no longer connected? Maybe when a write fails or by catching an exception that is thrown at some operation? I need this to be non-blocking and I want to do this in a way that the Channel can be re-established (i.e. a new channel to the same server is established) if the connection fails.


Solution

  • You'll get exceptions for read/write.

    At other times, if the channel is registered for read/write interest on a selector, when the channel is broken, select() will return, and the selection key for the channel will indicate readable/writable. You'll encounter an exception in the next read/write.