Register a SocketChannel and connect the remote address.

@param sock
the SocketChannel.
@param addr
the remote address.
@throws IOException
the IOException.
777908
void registerAndConnect(SocketChannel sock, InetSocketAddress addr)
            throws IOException {
        selectionKey = sock.register(selector, SelectionKey.OP_CONNECT);

        boolean immediateConnect = sock.connect(addr);
        if(LOGGER.isTraceEnabled()){
            LOGGER.trace("Connect to host=" + addr.getHostName() + ", hostString=" + addr.getHostString() + ", port=" + addr.getPort() + ", all=" + addr.getAddress() + ", local=" + sock.socket().getLocalSocketAddress());
        }
        if (immediateConnect) {
            onConnectSucceeded();
        }


    }
172404
private SocketChannel connectToHost(SocketAddress hostAddr)
            throws IOException
    {
        SocketChannel socket = null;
        while (socket == null) {
            try {
                socket = SocketChannel.open(hostAddr);
            }
            catch (java.net.ConnectException e) {
                LOG.warn("Joining host failed: " + e.getMessage() + " retrying..");
                try {
                    Thread.sleep(250); //  milliseconds
                }
                catch (InterruptedException dontcare) {}
            }
        }
        return socket;
    }
1244827
function(id, socket, adaptor) {
  EventEmitter.call(this);
  this.id = id;
  this.socket = socket;
  this.remoteAddress = {
    ip: socket.stream.remoteAddress,
    port: socket.stream.remotePort
  };
  this.adaptor = adaptor;

  var self = this;

  socket.on('close', this.emit.bind(this, 'disconnect'));
  socket.on('error', this.emit.bind(this, 'disconnect'));
  socket.on('disconnect', this.emit.bind(this, 'disconnect'));

  socket.on('pingreq', function(packet) {
    socket.pingresp();
  });

  socket.on('subscribe', this.adaptor.onSubscribe.bind(this.adaptor, this));

  socket.on('publish', this.adaptor.onPublish.bind(this.adaptor, this));

  this.state = ST_INITED;

  // TODO: any other events?
}
1020476
public static Transport UDPInstance(SocketAddress addr) throws IOException {
        DatagramSocket sock = new DatagramSocket();
        sock.setSoTimeout(getTimeout());
        sock.connect(addr);

        StreamTransport trans = new StreamTransport();
        trans.setStreams(new UDPInputStream(sock), new UDPOutputStream(sock));
        trans.setAddressLabel(addr.toString());
        return trans;
    }
474422
def _connect(self, sock, addr, timeout):
        """"""
        if self.connection:
            raise SocketClientConnectedError()

        if self.connector:
            raise SocketClientConnectingError()

        self.connect_deferred = Deferred(self.loop)
        self.sock = sock
        self.addr = addr
        self.connector = Connector(self.loop, sock, addr, timeout)
        self.connector.deferred.add_callback(self._connected)
        self.connector.deferred.add_errback(self._connect_failed)
        self.connector.start()

        return self.connect_deferred
810721
private void connect(String host, int port) throws SQLException, IOException {
    try {
      socket = Utils.createSocket(urlParser, host);
      if (options.socketTimeout != null) {
        socket.setSoTimeout(options.socketTimeout);
      }

      initializeSocketOption();

      // Bind the socket to a particular interface if the connection property
      // localSocketAddress has been defined.
      if (options.localSocketAddress != null) {
        InetSocketAddress localAddress = new InetSocketAddress(options.localSocketAddress, 0);
        socket.bind(localAddress);
      }

      if (!socket.isConnected()) {
        InetSocketAddress sockAddr =
            urlParser.getOptions().pipe == null ? new InetSocketAddress(host, port) : null;
        if (options.connectTimeout != 0) {
          socket.connect(sockAddr, options.connectTimeout);
        } else {
          socket.connect(sockAddr);
        }
      }

      handleConnectionPhases(host);

      connected = true;

      if (options.useCompression) {
        writer = new CompressPacketOutputStream(writer.getOutputStream(),
            options.maxQuerySizeToLog);
        reader = new DecompressPacketInputStream(
            ((StandardPacketInputStream) reader).getInputStream(),
            options.maxQuerySizeToLog);
        if (options.enablePacketDebug) {
          writer.setTraceCache(traceCache);
          reader.setTraceCache(traceCache);
        }
      }

      boolean mustLoadAdditionalInfo = true;
      if (globalInfo != null) {
        if (globalInfo.isAutocommit() == options.autocommit) {
          mustLoadAdditionalInfo = false;
        }
      }

      if (mustLoadAdditionalInfo) {
        Map<String, String> serverData = new TreeMap<>();
        if (options.usePipelineAuth && !options.createDatabaseIfNotExist) {
          try {
            sendPipelineAdditionalData();
            readPipelineAdditionalData(serverData);
          } catch (SQLException sqle) {
            if ("08".equals(sqle.getSQLState())) {
              throw sqle;
            }
            //in case pipeline is not supported
            //(proxy flush socket after reading first packet)
            additionalData(serverData);
          }
        } else {
          additionalData(serverData);
        }

        writer.setMaxAllowedPacket(Integer.parseInt(serverData.get("max_allowed_packet")));
        autoIncrementIncrement = Integer.parseInt(serverData.get("auto_increment_increment"));
        loadCalendar(serverData.get("time_zone"), serverData.get("system_time_zone"));

      } else {

        writer.setMaxAllowedPacket((int) globalInfo.getMaxAllowedPacket());
        autoIncrementIncrement = globalInfo.getAutoIncrementIncrement();
        loadCalendar(globalInfo.getTimeZone(), globalInfo.getSystemTimeZone());
      }

      reader.setServerThreadId(this.serverThreadId, isMasterConnection());
      writer.setServerThreadId(this.serverThreadId, isMasterConnection());

      activeStreamingResult = null;
      hostFailed = false;
    } catch (IOException | SQLException ioException) {
      ensureClosingSocketOnException();
      throw ioException;
    }
  }
1170878
protected synchronized void bind(InetAddress address, int lport)
        throws IOException
    {
       synchronized (fdLock) {
            if (!closePending && (socket == null || !socket.isBound())) {
                NetHooks.beforeTcpBind(fd, address, lport);
            }
        }
        socketBind(address, lport);
        if (socket != null)
            socket.setBound();
        if (serverSocket != null)
            serverSocket.setBound();
    }
392116
@Override
  public void register(final Identifier id, final InetSocketAddress addr) {
    LOG.log(Level.FINE, "id: " + id + " addr: " + addr);
    idToAddrMap.put(id, addr);
  }
665032
public void bind(InetSocketAddress address) throws IOException {
        if (listener != null) {
            listener.close();
            listener = null;
        }
        listener = ServerSocketChannel.open();
        listener.socket().bind(address);
    }
242210
public HttpListener addListener(InetAddrPort address)
        throws IOException
    {
        HttpListener listener = new SocketListener(address);
        listener.setHttpServer(this);
        _listeners.add(listener);
        addComponent(listener);
        return listener;
    }
814082
public static SSLServerSocketChannel open(int port, SSLContext sslContext) throws IOException
    {
        return open(new InetSocketAddress(port), sslContext);
    }
944656
def get_client_sock(addr):
    ""
    s = _socket.create_connection(addr)
    s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, True)
    s.setblocking(False)
    return s
791969
@Override
	public void addInputChannel(RemoteInputChannel listener) throws IOException {
		checkError();

		inputChannels.putIfAbsent(listener.getInputChannelId(), listener);
	}
267532
synchronized void doConnect(InetAddress address, int port, int timeout) throws IOException {
        synchronized (fdLock) {
            if (!closePending && (socket == null || !socket.isBound())) {
                NetHooks.beforeTcpConnect(fd, address, port);
            }
        }
        try {
            BlockGuard.getThreadPolicy().onNetwork();
            socketConnect(address, port, timeout);
            /* socket may have been closed during poll/select */
            synchronized (fdLock) {
                if (closePending) {
                    throw new SocketException ("Socket closed");
                }
            }
            // If we have a ref. to the Socket, then sets the flags
            // created, bound & connected to true.
            // This is normally done in Socket.connect() but some
            // subclasses of Socket may call impl.connect() directly!
            if (socket != null) {
                socket.setBound();
                socket.setConnected();
            }
        } catch (IOException e) {
            close();
            throw e;
        }
    }
992576
private static ChannelFuture socksConnect(Channel channel, InetSocketAddress remoteAddress)
    {
        channel.write(createHandshake(remoteAddress));
        return ((Socks4HandshakeHandler) channel.getPipeline().get("handshake")).getChannelFuture();
    }
210817
ChannelFuture connect(final InetSocketAddress serverSocketAddress) {
		checkState(bootstrap != null, "Client has not been initialized yet.");

		// --------------------------------------------------------------------
		// Child channel pipeline for accepted connections
		// --------------------------------------------------------------------

		bootstrap.handler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel channel) throws Exception {

				// SSL handler should be added first in the pipeline
				if (clientSSLFactory != null) {
					SslHandler sslHandler = clientSSLFactory.createNettySSLHandler(
							serverSocketAddress.getAddress().getCanonicalHostName(),
							serverSocketAddress.getPort());
					channel.pipeline().addLast("ssl", sslHandler);
				}
				channel.pipeline().addLast(protocol.getClientChannelHandlers());
			}
		});

		try {
			return bootstrap.connect(serverSocketAddress);
		}
		catch (ChannelException e) {
			if ((e.getCause() instanceof java.net.SocketException &&
					e.getCause().getMessage().equals("Too many open files")) ||
				(e.getCause() instanceof ChannelException &&
						e.getCause().getCause() instanceof java.net.SocketException &&
						e.getCause().getCause().getMessage().equals("Too many open files")))
			{
				throw new ChannelException(
						"The operating system does not offer enough file handles to open the network connection. " +
								"Please increase the number of available file handles.", e.getCause());
			}
			else {
				throw e;
			}
		}
	}
1023203
@Override
    public boolean setAddress(String addr)
    {
        address = new IpcAddress(addr);

        InetSocketAddress sock = (InetSocketAddress) address.address();
        String fake = sock.getAddress().getHostAddress() + ":" + sock.getPort();
        return super.setAddress(fake);
    }