Specify connection timeout in java.nio

大憨熊 提交于 2019-12-18 04:55:08

问题


Using non-blocking I/O, the code for connecting to a remote address looks something like:

SocketChannel channel = SelectorProvider.provider().openSocketChannel();
channel.configureBlocking(false);
channel.connect(address);

The connection process will then have to be finished by invoking finishConnect() on the channel when some selector says the corresponding key isConnectable().

Is there a way to specify the connection timeout when using this idiom?


回答1:


Interesting question. I'm not sure that nio itself provides a solution.

In my experience, I've run a Callable to attempt the connection, and then used the Future to poll for a response, using 'interval' and 'timeout' variables to loop and Thread.sleep() for a response.

Hopefully that points you in a useful direction ...

Also, I suggest you take a look at Apache Mina (you could describe Mina as an nio framework). It handles a lot of this kind of stuff for you, for example in the StreamIoHandler http://mina.apache.org/report/trunk/apidocs/org/apache/mina/handler/stream/StreamIoHandler.html




回答2:


The question doesn't really make sense. Timeouts are for blocking mode. If you want that, leave the channel in blocking mode and call channel.socket().connect(address, timeout);. If you want non-blocking mode, use your current code; then create a Selector; register the channel for OP_CONNECT; when you get it call finishConnect(), and if that returns true deregister OP_CONNECT and continue with the rest of your code.



来源:https://stackoverflow.com/questions/2563934/specify-connection-timeout-in-java-nio

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