Chris Chris - 3 months ago 15
Java Question

Create several outgoing connections simultaneously in Java NIO

I'm using Java NIO for a peer to peer protocol and need to create many simultaneous connections of which many will fail. Unfortunately, it seems as if I need to wait for a connection to be established before creating the next one, otherwise I'll get a "BindException: Cannot assign requested address: connect". Does anyone have an idea how to fix this?

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);
}
}

Answer

You can't use the connection before it has finished connecting but you can have any number of pending connections

You can either

  • poll you connecting connection to see if they have connected yet, or
  • add the connection to a Selector by registering an OP_CONNECT.

In either case I suggest calling finishConnect() to ensure it is ready for use.