我使用Java作为对等协议,需要创建许多同时连接,其中许多连接将失败。不幸的是,在创建下一个连接之前,我似乎需要等待建立一个连接,否则我将得到一个"BindException:无法分配请求的地址:连接“。有谁知道怎么解决这个问题吗?
for (NetworkAddress address : addresses) {
if (isConnectedTo(address)) {
continue;
}
try {
SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress(address.toInetAddress(), address.getPort()));
// admittedly, 20 seconds is quite long
long timeout = System.currentTimeMillis() + 20_000;
while (!channel.finishConnect() && System.currentTimeMillis() < timeout) {
// Without this loop, I get said exception
}
if (!channel.finishConnect()) {
channel.close();
continue;
}
ConnectionInfo connection = new ConnectionInfo(ctx, CLIENT,
address,
listener,
requestedObjects, 0
);
connections.put(
connection,
channel.register(selector, OP_READ | OP_WRITE, connection)
);
} catch (NoRouteToHostException | AsynchronousCloseException ignore) {
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
}发布于 2016-08-28 00:22:29
无法在连接完成之前使用该连接,但可以有任意数量的挂起连接
你可以
在这两种情况下,我建议调用finishConnect()以确保它已准备好使用。
https://stackoverflow.com/questions/39180086
复制相似问题