java SocketChannel 超时不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2866557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 23:12:21  来源:igfitidea点击:

Timeout for SocketChannel doesn't work

javasocketchannel

提问by user345171

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

我想使用 aSocketChannel并为其读/写方法设置超时。我试图为拥有我的 Socket 设置超时,SocketChannel如下所示:

channel.socket().setSoTimeout(TIMEOUT);

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

但这不起作用。还有其他解决方案吗?

回答by luke

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;
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.

根据您设置的 socketTimeOut,从wrappedChannel 读取将超时。

回答by Eugene Chung

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.

如果您熟悉使用 Java Selector,则可以使用 selector 自己模拟套接字超时。看 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 closeSocketChannel. If you want to use SocketChannel after timeout, you cannot use the InterruptibleChannel feature.

使用 Thread.interrupt() 应该小心。SocketChannel 是 InterruptibleChannel。当您阅读 InterruptibleChannel 的描述时,Thread.interrupt() 会导致关闭SocketChannel。如果要在超时后使用 SocketChannel,则不能使用 InterruptibleChannel 功能。

回答by Bat0u89

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

您还可以考虑使您的频道不可阻塞并仅使用 System.currentTimeMillis()。