private void socketConnected(InetSocketAddress remoteAddress, SocketChannel channel) { final ISocketChannel socketChannel = socketChannelFactory.createClientChannel(channel); final PendingHandshakeConnection conn = new PendingHandshakeConnection(socketChannel, remoteAddress, OUTGOING); if (socketChannel.requiresHandshake()) { asyncHandshake(conn); } else { conn.handshakeSuccess = true; handshakeCompletedConnections.add(conn); } }
private void finishConnect(SelectionKey connectableKey) { SocketChannel channel = (SocketChannel) connectableKey.channel(); IPCHandle handle = (IPCHandle) connectableKey.attachment(); boolean connected = false; try { connected = channel.finishConnect(); if (connected) { SelectionKey channelKey = channel.register(selector, SelectionKey.OP_READ); final ISocketChannel clientChannel = socketChannelFactory.createClientChannel(channel); if (clientChannel.requiresHandshake()) { asyncHandshake(clientChannel, handle, channelKey); } else { connectionEstablished(handle, channelKey, clientChannel); } } } catch (IOException e) { LOGGER.warn("Exception finishing connect", e); } finally { if (!connected) { LOGGER.warn("Failed to finish connect to {}", handle.getRemoteAddress()); close(connectableKey, channel); } } }
public static ISocketChannel establishReplicaConnection(INcApplicationContext appCtx, InetSocketAddress location) throws IOException { final SocketChannel socketChannel = SocketChannel.open(); NetworkUtil.configure(socketChannel); socketChannel.connect(location); // perform handshake in a non-blocking mode socketChannel.configureBlocking(false); final ISocketChannelFactory socketChannelFactory = appCtx.getServiceContext().getControllerService().getNetworkSecurityManager().getSocketChannelFactory(); final ISocketChannel clientChannel = socketChannelFactory.createClientChannel(socketChannel); if (clientChannel.requiresHandshake() && !clientChannel.handshake()) { throw new IllegalStateException("handshake failure"); } // switch to blocking mode after handshake success socketChannel.configureBlocking(true); return clientChannel; }
private void establishPendingConnections() { for (IPCHandle handle : workingPendingConnections) { SocketChannel channel = null; SelectionKey channelKey = null; try { channel = SocketChannel.open(); register(channel); if (channel.connect(handle.getRemoteAddress())) { channelKey = channel.register(selector, SelectionKey.OP_READ); final ISocketChannel clientChannel = socketChannelFactory.createClientChannel(channel); if (clientChannel.requiresHandshake()) { asyncHandshake(clientChannel, handle, channelKey); } else { connectionEstablished(handle, channelKey, clientChannel); } } else { channelKey = channel.register(selector, SelectionKey.OP_CONNECT); handle.setKey(channelKey); channelKey.attach(handle); } } catch (IOException e) { LOGGER.error("Failed to accept channel ", e); close(channelKey, channel); handle.setState(HandleState.CLOSED); } } workingPendingConnections.clear(); }