Timeout for SocketChannel doesn't work

user345171 picture user345171 · May 19, 2010 · Viewed 14.6k times · Source

I want to use a SocketChannel and to have a timeout for its read/write methods. I've tried to set a timeout for the Socket that owns my SocketChannel like this:

channel.socket().setSoTimeout(TIMEOUT);

but that doesn't work. Is there any other solution?

Answer

luke picture luke · Feb 5, 2012

According to this article, SocketChannel will not timeout for its read operation but you can get this effect from reading from the channel in another way.

SocketChannel socketChannel;
socketChannel.socket().setSocketTimeout(500);
InputStream inStream = socketChannel.socket().getInputStream();
ReadableByteChannel wrappedChannel = Channels.newChannel(inStream);

reading from the wrappedChannel will timeout according to the socketTimeOut you have set.