Either:
You are using a
Selector
, in which case you have a select timeout which you can play with, and if it goes off (select(timeout)
returns zero) you close all the registered channels, orYou are using blocking mode, in which case you might think you should be able to call
Socket.setSoTimeout()
on the underlying socket (SocketChannel.socket()
), and trap theSocketTimeoutException
that is thrown when the timeout expires duringread()
, but you can't, because it isn't supported for sockets originating as channels, orYou are using non-blocking mode without a
Selector
, in which case you need to change to case (1).
So you either need to use case (1) or a java.net.Socket
directly.