Timeout for SocketChannel doesn't work

混江龙づ霸主 提交于 2019-11-26 16:59:15

问题


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?


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/2866557/timeout-for-socketchannel-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!