nio中指定连接超时

nio中指定连接超时

本文介绍了在java.nio中指定连接超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

使用非阻塞I / O,连接到远程地址的代码看起来像:

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

然后必须通过调用 finishConnect / code>。

有一些选择器表示对应的键 isConnectable()一个方法来指定使用这个成语的连接超时?

解决方案

这个问题没有什么意义。超时用于阻塞模式。如果你想要,离开通道在阻塞模式,并调用 channel.socket()。connect(address,timeout); 。如果你想要非阻塞模式,使用你当前的代码;然后创建一个Selector;注册 OP_CONNECT 的通道;当你得到 finishConnect(),,如果返回true deregister OP_CONNECT 并继续其余的代码。


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?

解决方案

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.

这篇关于在java.nio中指定连接超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 14:51