SocketChannel 的超时不起作用

发布于 2024-09-02 06:42:24 字数 173 浏览 8 评论 0原文

我想使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

猫七 2024-09-09 06:42:24

根据此 文章,SocketChannel 的读取操作不会超时,但您可以通过其他方式从通道读取来获得此效果。

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

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

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.

中性美 2024-09-09 06:42:24

如果您熟悉使用 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.

月亮邮递员 2024-09-09 06:42:24

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文