问题描述
使用非阻塞I / O,连接到远程地址的代码看起来像:
SocketChannel channel = SelectorProvider.provider()。openSocketChannel();
channel.configureBlocking(false);
channel.connect(address);
然后必须通过调用 有一些选择器表示对应的键 这个问题没有什么意义。超时用于阻塞模式。如果你想要,离开通道在阻塞模式,并调用 Using non-blocking I/O, the code for connecting to a remote address looks something like: The connection process will then have to be finished by invoking 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 这篇关于在java.nio中指定连接超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! finishConnect / code>。
isConnectable()
一个方法来指定使用这个成语的连接超时? channel.socket()。connect(address,timeout);
。如果你想要非阻塞模式,使用你当前的代码;然后创建一个Selector;注册 OP_CONNECT
的通道;当你得到 finishConnect(),
,如果返回true deregister OP_CONNECT
并继续其余的代码。SocketChannel channel = SelectorProvider.provider().openSocketChannel();
channel.configureBlocking(false);
channel.connect(address);
finishConnect()
on the channel when some selector says the corresponding key isConnectable()
.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.