Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaNIO-非阻塞连接_Java_Sockets_Nio_Channel - Fatal编程技术网

JavaNIO-非阻塞连接

JavaNIO-非阻塞连接,java,sockets,nio,channel,Java,Sockets,Nio,Channel,在客户端的非阻塞连接中,可能是服务器未启动,无法建立连接。我使用选择器等待OP_CONNECT确定是否可以通过以下方式建立连接: connection = SocketChannel.open(); connection.configureBlocking(false); // Kick off connection establishment connection.connect(hostAddress); connection.register(selector, SelectionKe

在客户端的非阻塞连接中,可能是服务器未启动,无法建立连接。我使用选择器等待OP_CONNECT确定是否可以通过以下方式建立连接:

connection = SocketChannel.open();
connection.configureBlocking(false);

// Kick off connection establishment
connection.connect(hostAddress);

connection.register(selector, SelectionKey.OP_CONNECT);
this.selector.select(2000);

// Iterate over the set of keys for which events are available
Iterator<SelectionKey> selectedKeys = this.selector.selectedKeys().iterator();
if (!selectedKeys.hasNext()) {
    throw new IllegalStateException("\"Could not connect to \" + hostAddress");
}
SelectionKey key = selectedKeys.next();
boolean valid = key.isValid();

if (!key.isConnectable()) {
    throw new IllegalStateException("\"Could not connect to \" + hostAddress");
}
finishConnection(key);
connection=SocketChannel.open();
连接.配置阻塞(false);
//启动连接建立
connection.connect(主机地址);
连接.寄存器(选择器,SelectionKey.OP_CONNECT);
this.selector.select(2000);
//迭代事件可用的键集
迭代器selectedKeys=this.selector.selectedKeys().Iterator();
如果(!selectedKeys.hasNext()){
抛出新的IllegalStateException(“\”无法连接到“\”+hostAddress”);
}
SelectionKey=selectedKeys.next();
boolean valid=key.isValid();
如果(!key.isConnectable()){
抛出新的IllegalStateException(“\”无法连接到“\”+hostAddress”);
}
完成连接(键);

但是,即使我没有启动服务器,
键.isConnectable()
也会返回true。。。我不知道;我不明白为什么会这样,以及如何确保我只在连接时再次调用选择器。select(),只是为了获取信息:如果你不需要低级别的NIO,请看看Netty:它使非阻塞IO变得非常容易。这样做没有多大意义。您在这里所做的就是使用select()实现阻塞模式。这就是您真正的代码所做的,将通道保持在阻塞模式下,使用带有超时参数的connect()并在成功连接时进入非阻塞模式会更简单。事实上,我认为TCP客户机根本不需要NIO。