public Future<Boolean> connect(InetSocketAddressWrapper addressWrapper) throws IOException { if (addressWrapper == null) { throw new NullPointerException("Null Address"); } // Remove addr from removed set this.removedAddrSet.remove(addressWrapper.getInetSocketAddress()); SocketChannel socketChannel = SocketChannel.open(); this.configureSocketChannel(socketChannel); ConnectFuture future = new ConnectFuture(addressWrapper); if (!socketChannel.connect(addressWrapper.getInetSocketAddress())) { this.selectorManager.registerChannel(socketChannel, SelectionKey.OP_CONNECT, future); } else { this.addSession(this.createSession(socketChannel, addressWrapper)); future.setResult(true); } return future; }
@Override public void onConnect(SelectionKey key) throws IOException { key.interestOps(key.interestOps() & ~SelectionKey.OP_CONNECT); ConnectFuture future = (ConnectFuture) key.attachment(); if (future == null || future.isCancelled()) { key.channel().close(); key.cancel(); return; } try { if (!((SocketChannel) key.channel()).finishConnect()) { future.failure( new IOException( "Connect to " + SystemUtils.getRawAddress( future.getInetSocketAddressWrapper().getInetSocketAddress()) + ":" + future.getInetSocketAddressWrapper().getInetSocketAddress().getPort() + " fail")); } else { key.attach(null); this.addSession( this.createSession( (SocketChannel) key.channel(), future.getInetSocketAddressWrapper())); future.setResult(Boolean.TRUE); } } catch (Exception e) { future.failure(e); key.cancel(); throw new IOException( "Connect to " + SystemUtils.getRawAddress( future.getInetSocketAddressWrapper().getInetSocketAddress()) + ":" + future.getInetSocketAddressWrapper().getInetSocketAddress().getPort() + " fail," + e.getMessage()); } }