如何在阻塞模式NIO中实现超时? [英] How does one implement a timeout in blocking mode NIO?

查看:375
本文介绍了如何在阻塞模式NIO中实现超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有使用任何选择器或类似的东西。我只有一个简单的 ServerSocketChannel 监听和一个 SocketChannel 以阻塞模式连接到它。我想对连接施加超时,但 SocketChannel.socket()。setSoTimeout()不起作用。

I'm not using any selectors or anything like that. I just have a simple ServerSocketChannel listening and a SocketChannel connecting to it in blocking mode. I want to impose a timeout on the connection, but SocketChannel.socket().setSoTimeout() does not work.

我尝试让后台线程休眠30秒并检查变量是否仍然 null (因为它会阻止等待读入该变量)但我无法正确同步变量,因为我无法访问我的匿名类中的局部变量。

I tried making a background thread sleep for 30 seconds and checking if a variable is still null (since it will block waiting to read into that variable) but I couldn't synchronize the variable properly in that I could not access the local variable in my anonymous class.

还有其他方法要做到这一点吗?

Are there other ways to accomplish this?

更新:我说错了我的问题。我还希望读取操作以及连接本身都有超时。

Update: I've worded my question wrong. I also want to have a timeout on read operations as well as the connection itself.

推荐答案

setSoTimeout( )设置读取超时,而不是连接超时,并且由于某种原因,它在 SocketChannels 上完全不起作用,即使在阻塞模式下,甚至包裹流。

setSoTimeout() sets a read timeout, not a connect timeout, and for some reason it doesn't work at all on SocketChannels, even in blocking mode, and even with wrapped streams.

您正在寻找的方法是 channel.socket()。connect()有两个参数。

The method you are looking for is channel.socket().connect() with two arguments.

这篇关于如何在阻塞模式NIO中实现超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆