SocketChannel 的超时不起作用
我想使用 SocketChannel 并为其读/写方法设置超时。我尝试为拥有我的 SocketChannel 的 Socket 设置超时,如下所示:
channel.socket().setSoTimeout(TIMEOUT);
但这不起作用。还有其他解决办法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据此 文章,SocketChannel 的读取操作不会超时,但您可以通过其他方式从通道读取来获得此效果。
从wrappedChannel读取将根据您设置的socketTimeOut超时。
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.
reading from the wrappedChannel will timeout according to the socketTimeOut you have set.
如果您熟悉使用 Java 选择器,则可以使用选择器自己模拟套接字超时。查看 sun.nio.ch.SocketAdaptor 会很有帮助。
使用Thread.interrupt()应该小心。
SocketChannel是InterruptibleChannel。当您阅读 InterruptibleChannel 的描述时,Thread.interrupt() 会导致关闭 SocketChannel。
如果要在超时后使用SocketChannel,则不能使用InterruptibleChannel 功能。
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.
您还可以考虑使通道不可阻塞并仅使用 System.currentTimeMillis()。
You could also consider making your channel non-blockable and just using System.currentTimeMillis().