- public void connect(byte[] their_node_id, SocketAddress remote) throws IOException {
- SocketChannel chan = SocketChannel.open(remote);
+ public void connect(byte[] their_node_id, SocketAddress remote, int timeout_ms) throws IOException {
+ SocketChannel chan = SocketChannel.open();
+ chan.configureBlocking(false);
+ Selector open_selector = Selector.open();
+ chan.register(open_selector, SelectionKey.OP_CONNECT);
+ if (!chan.connect(remote)) {
+ open_selector.select(timeout_ms);
+ }
+ if (!chan.finishConnect()) { // Note that this may throw its own IOException if we failed for another reason
+ throw new IOException("Timed out");
+ }