Timeout for SocketChannel doesn't work
Asked Answered
P

3

17

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?

Planimetry answered 19/5, 2010 at 14:42 Comment(3)
Unfortunately, SocketChannel doesn't support the setSoTimeout method directly. Using it will sadly be disregarded.Handy
SocketChannel implements the InterruptibleChannel interface, which means that you could create a separate thread before entering your read() call, have that other thread set a timer and, when the timer expires, it could interrupt the thread in which your SocketChannel read() call is blocking. If the read() call returns first, you could have it kill the timer thread.Vocalize
@StevensMiller And the channel will be closed, and the read will throw ClosedByInterruptException. Not very useful. I was told this bizarre implementation is mandated by the behaviour of Linux.Enfield
C
13

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.

Closure answered 5/2, 2012 at 15:41 Comment(2)
This is not the correct way to do this, only a workaround. The proper way is to use the Selector.select(timeout) in a loop and check the soTimeout/connectTimeout with an if-checkPeen
setSocketTimeout is now setSoTimeout, but works the same way.Eli
E
3

If you are familiar with using Java Selector, you can emulate socket timeout yourself using selector. It is helpful to see sun.nio.ch.SocketAdaptor.

It should be careful to use Thread.interrupt(). SocketChannel is InterruptibleChannel. As you read the description of InterruptibleChannel, Thread.interrupt() causes to close SocketChannel. If you want to use SocketChannel after timeout, you cannot use the InterruptibleChannel feature.

Eamon answered 22/8, 2013 at 8:31 Comment(0)
B
-1

You could also consider making your channel non-blockable and just using System.currentTimeMillis().

Bibelot answered 14/10, 2012 at 20:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.