在客户端的非阻塞连接中,可能是服务器未启动且无法建立连接的情况。我使用选择器等待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);
但是,即使我没有启动服务器,key.isConnectable()
也会返回true ...我不明白为什么会这样,以及如何确保我只再次调用selector.select()
当我连接时