Create socket to the given host
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;
    }
743834
def connected_socket(address, timeout=3):
    
    sock = socket.create_connection(address, timeout)
    yield sock
    sock.close()
948011
def prepare_socket(bind_addr, family, type, proto, nodelay, ssl_adapter):
        """"""
        sock = socket.socket(family, type, proto)
        prevent_socket_inheritance(sock)

        host, port = bind_addr[:2]
        IS_EPHEMERAL_PORT = port == 0

        if not (IS_WINDOWS or IS_EPHEMERAL_PORT):
            """Enable SO_REUSEADDR for the current socket.

            Skip for Windows (has different semantics)
            or ephemeral ports (can steal ports from others).

            Refs:
            * https://msdn.microsoft.com/en-us/library/ms740621(v=vs.85).aspx
            * https://github.com/cherrypy/cheroot/issues/114
            * https://gavv.github.io/blog/ephemeral-port-reuse/
            """
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if nodelay and not isinstance(bind_addr, str):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

        if ssl_adapter is not None:
            sock = ssl_adapter.bind(sock)

        # If listening on the IPV6 any address ('::' = IN6ADDR_ANY),
        # activate dual-stack. See
        # https://github.com/cherrypy/cherrypy/issues/871.
        listening_ipv6 = (
            hasattr(socket, 'AF_INET6')
            and family == socket.AF_INET6
            and host in ('::', '::0', '::0.0.0.0')
        )
        if listening_ipv6:
            try:
                sock.setsockopt(
                    socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0,
                )
            except (AttributeError, socket.error):
                # Apparently, the socket option is not available in
                # this machine's TCP stack
                pass

        return sock
511992
def get_socket(host, port, timeout=None):
    
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            sock = socket(af, socktype, proto)
            if timeout is not None:
                sock.settimeout(timeout)
            sock.connect(sa)
            return sock

        except error:
            if sock is not None:
                sock.close()

    raise error
18022
public static TcpClient<ByteBuf, ByteBuf> newClient(String host, int port) {
        return newClient(new InetSocketAddress(host, port));
    }
1108036
def _create_socket(self):
        
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s = ssl.wrap_socket(s)
        s.connect((self.host, self.__port))
        s.settimeout(self.timeout)
        return s
1127679
def serve(self):
    """"""
    # We don't have to trap KeyboardInterrupt or SystemExit here,

    # Select the appropriate socket
    if isinstance(self.bind_addr, basestring):
      # AF_UNIX socket

      # So we can reuse the socket...
      try: os.unlink(self.bind_addr)
      except: pass

      # So everyone can access the socket...
      try: os.chmod(self.bind_addr, 0777)
      except: pass

      info = [(socket.AF_UNIX, socket.SOCK_STREAM, 0, "", self.bind_addr)]
    else:
      # AF_INET or AF_INET6 socket
      # Get the correct address family for our host (allows IPv6 addresses)
      host, port = self.bind_addr
      try:
        info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                      socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
      except socket.gaierror:
        # Probably a DNS issue. Assume IPv4.
        info = [(socket.AF_INET, socket.SOCK_STREAM, 0, "", self.bind_addr)]

    self.socket = None
    msg = "No socket could be created"
    for res in info:
      af, socktype, proto, canonname, sa = res
      #~ print res
      try:
        self.bind(af, socktype, proto)
      except socket.error, msg:
        if self.socket:
          self.socket.close()
        self.socket = None
        continue
      break
    if not self.socket:
      raise socket.error, msg

    self.socket.listen(self.request_queue_size)
    with closing(self.socket):
      while True:
        try:
          s, addr = yield sockets.Accept(self.socket, timeout=-1)
          s.settimeout(self.sockoper_timeout)
        except Exception, exc:
          # make acceptor more robust in the face of weird
          # accept bugs, XXX: but we might get a infinite loop

          #~ import warnings
          #~ warnings.warn("Accept thrown an exception: %s" % exc)

          import traceback
          traceback.print_exc()
          continue

        environ = self.environ.copy()
        environ["SERVER_SOFTWARE"] = self.version
        # set a non-standard environ entry so the WSGI app can know what
        # the *real* server protocol is (and what features to support).
        # See http://www.faqs.org/rfcs/rfc2145.html.
        environ["ACTUAL_SERVER_PROTOCOL"] = self.protocol
        environ["SERVER_NAME"] = self.server_name

        if isinstance(self.bind_addr, basestring):
          # AF_UNIX. This isn't really allowed by WSGI, which doesn't
          # address unix domain sockets. But it's better than nothing.
          environ["SERVER_PORT"] = ""
        else:
          environ["SERVER_PORT"] = str(self.bind_addr[1])
          # optional values
          # Until we do DNS lookups, omit REMOTE_HOST
          environ["REMOTE_ADDR"] = addr[0]
          environ["REMOTE_PORT"] = str(addr[1])

        conn = self.ConnectionClass(s, self.wsgi_app, environ,
          self.sendfile_timeout)
        yield events.AddCoro(conn.run, prio=priority.LAST if
                                     self.sockaccept_greedy else priority.FIRST)
80728
def connect(self, (host, port)):
        '''
        
        '''
        self._host = "%s:%s" % (host, port)
        self._sock = EventSocket(
            read_cb=self._sock_read_cb,
            close_cb=self._sock_close_cb,
            error_cb=self._sock_error_cb,
            debug=self.connection.debug,
            logger=self.connection.logger)
        if self.connection._sock_opts:
            for k, v in self.connection._sock_opts.iteritems():
                family, type = k
                self._sock.setsockopt(family, type, v)
        self._sock.setblocking(False)
        self._sock.connect(
            (host, port), timeout=self.connection._connect_timeout)
        self._heartbeat_timeout = None
523323
def connect(self, host, port):
        ''''''
        conn = connection.Connection(host, port,
            reconnection_backoff=self._reconnection_backoff,
            auth_secret=self._auth_secret,
            timeout=self._connect_timeout,
            **self._identify_options)
        if conn.alive():
            conn.setblocking(0)
        self.add(conn)
        return conn
257070
function Client(host, port) {
  this.host = host;
  this.port = port;
  this.socket = null;
  this.connected = false;

  // Useful protocol information
  this.req_counter = 1;
  this.req_table = {};

  this.on_handlers = {
    connect: function() {},
    print_string: function(m) {},
    presentation_start: function (pid) {},
    presentation_end: function (pid) {},
    new_package: function(p) {},
    debug_activate: function(obj) {},
    debug_setup: function(obj) {},
    debug_return: function(obj) {},
    profile_command_complete: function(msg) {},
    disconnect: function() {}
  }

  // Bootstrap the reading state
  this.setup_read(6, this.header_complete_callback);
}
476425
public static HttpClient<ByteBuf, ByteBuf> newClient(String host, int port) {
        return newClient(new InetSocketAddress(host, port));
    }
781533
public static Proxy socksProxy(String host, int port) {
        return new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(Objects.requireNonNull(host), port));
    }
1254485
def _connect(self):
        ""
        self.socket = socket.socket()
        self.socket.connect((self.config['host'], self.config['port']))
        self.cmd("NICK %s" % self.config['nick'])
        self.cmd("USER %s %s bla :%s" %
                (self.config['ident'], self.config['host'], self.config['realname']))
132119
@PublicEvolving
	public void write_to_socket(String host, Integer port, SerializationSchema<PyObject> schema) throws IOException {
		stream.writeToSocket(host, port, new PythonSerializationSchema(schema));
	}
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;
    }
  }
198488
def build_socket(self):
        
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.settimeout(self.SOCKET_TIMEOUT)
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            # Check if TLS
            if self.request_object.protocol == 'https':
                self.sock = ssl.wrap_socket(self.sock, ciphers=self.CIPHERS)
            self.sock.connect(
                (self.request_object.dest_addr, self.request_object.port))
        except socket.error as msg:
            raise errors.TestError(
                'Failed to connect to server',
                {
                    'host': self.request_object.dest_addr,
                    'port': self.request_object.port,
                    'proto': self.request_object.protocol,
                    'message': msg,
                    'function': 'http.HttpUA.build_socket'
                })
1161664
def connect(self, (host, port)):
        '''
        
        '''
        super(GeventTransport, self).connect((host, port), klass=socket.socket)