3

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.

jbx
  • 21,365
  • 18
  • 90
  • 144

1 Answers1

3

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.

irreputable
  • 44,725
  • 9
  • 65
  • 93
  • Thanks! That seems to be the way it works also for connection failures, so makes sense also for read/write. – jbx Jan 16 '12 at 21:43
  • 1
    *when the channel is broken, select() will return, and the selection key for the channel will indicate readable/writable*, this is not true, while I am reading from the SocketChannel, the cable is unplugged, `select()` keeps returning **0** and the channel will never be selected again. If I read from or write to the channel ignoring its readable/writable state, `read()` does not return **-1**, it keeps returning **0**, and `write()` does not throw exception. Currently I find no way to detect socket disconnection, someone gives me a clue? – neevek Dec 23 '12 at 04:59
  • 1
    @bot_bot, you want to take a look at [this question](http://stackoverflow.com/questions/14010194/detecting-socket-disconnection) and the answers. – neevek Aug 27 '15 at 04:00