Connect to the proxy and perform a handshake requesting a connection.

        Return the open socket on success, or the exception on failure.
541119
async def _connect_one(self, remote_address):
        '''
        '''
        loop = asyncio.get_event_loop()

        for info in await loop.getaddrinfo(str(self.address.host), self.address.port,
                                           type=socket.SOCK_STREAM):
            # This object has state so is only good for one connection
            client = self.protocol(remote_address, self.auth)
            sock = socket.socket(family=info[0])
            try:
                # A non-blocking socket is required by loop socket methods
                sock.setblocking(False)
                await loop.sock_connect(sock, info[4])
                await self._handshake(client, sock, loop)
                self.peername = sock.getpeername()
                return sock
            except (OSError, SOCKSProtocolError) as e:
                exception = e
                # Don't close the socket because of an asyncio bug
                # see https://github.com/kyuupichan/aiorpcX/issues/8
        return exception
720002
def bind(self, *pos, **kw):
        
        proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy
        if not proxy_type or self.type != socket.SOCK_DGRAM:
            return _orig_socket.bind(self, *pos, **kw)

        if self._proxyconn:
            raise socket.error(EINVAL, "Socket already bound to an address")
        if proxy_type != SOCKS5:
            msg = "UDP only supported by SOCKS5 proxy type"
            raise socket.error(EOPNOTSUPP, msg)
        super(socksocket, self).bind(*pos, **kw)

        # Need to specify actual local port because
        # some relays drop packets if a port of zero is specified.
        # Avoid specifying host address in case of NAT though.
        _, port = self.getsockname()
        dst = ("0", port)

        self._proxyconn = _orig_socket()
        proxy = self._proxy_addr()
        self._proxyconn.connect(proxy)

        UDP_ASSOCIATE = b"\x03"
        _, relay = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst)

        # The relay is most likely on the same host as the SOCKS proxy,
        # but some proxies return a private IP address (10.x.y.z)
        host, _ = proxy
        _, port = relay
        super(socksocket, self).connect((host, port))
        super(socksocket, self).settimeout(self._timeout)
        self.proxy_sockname = ("0.0.0.0", 0)
416938
def open_connection
      @connection = TCPSocket.new(server, port)
      @socket = OpenSSL::SSL::SSLSocket.new(@connection) if @connection
      
      @socket.sync_close = true
      @socket.connect

      get_frame
    end
265425
@SuppressWarnings("unused")
    public URLConnection openConnection(URL url, Proxy proxy) throws IOException {
        try {
            return (URLConnection) _openConnectionProxy.invoke(getInstance(), new Object[] { url, proxy });
        } catch (Exception e) {
            FFDCFilter.processException(e, getClass().getName(), "openConnection", new Object[] { url, proxy });
            return null;
        }
    }
775818
def __connect(self):
        """"""
        try:
            logger.debug("Socket connecting to %s:%s", self.host, self.port)
            self.sock.connect((self.host, self.port))
        except socket.error as e:
            logger.exception("socket error %s", e)
            logger.error("Closing socket and recreating a new one.")
            self.sock.close()
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.connect((self.host, self.port))
169068
def connect(self):
        
        try:
            self.sock.connect((self.host, self.port))
            return self.sock
        except socket.error as ex:
            logging.error('Exception while connecting socket on %s:%s - Error %s' % (self.host, self.port, ex))
            raise
        except Exception as ex:
            logging.exception('Exception while connecting socket on %s:%s - Error %s' % (self.host, self.port, ex))
            raise
1354204
public HandshakerResp send(HandshakerReq req) throws InterruptedException, IOException {
    maybeThrowIoException();
    if (!responseQueue.isEmpty()) {
      throw new IOException("Received an unexpected response.");
    }
    writer.onNext(req);
    Optional<HandshakerResp> result = responseQueue.take();
    if (!result.isPresent()) {
      maybeThrowIoException();
    }
    return result.get();
  }
1324741
def attempt_connection(self):
        
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)

        self.receiver_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.receiver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.receiver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        self.receiver_socket.bind(('', MCAST_PORT))
        mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
        self.receiver_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        if not self.socket or not self.receiver_socket:
            raise exception.ConnectFailedException()
777588
def proxy(host='localhost', port=4304, flags=0, persistent=False,
          verbose=False, ):
    

    # resolve host name/port
    try:
        gai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM,
                                 socket.IPPROTO_TCP)
    except socket.gaierror as err:
        raise ConnError(*err.args)

    # gai is a (non empty) list of tuples, search for the first working one
    assert gai
    for (family, _type, _proto, _, sockaddr) in gai:
        assert _type is socket.SOCK_STREAM and _proto is socket.IPPROTO_TCP
        owp = _Proxy(family, sockaddr, flags, verbose)
        try:
            # check if there is an owserver listening
            owp.ping()
        except ConnError as err:
            # no connection, go over to next sockaddr
            lasterr = err.args
            continue
        else:
            # ok, live owserver found, stop searching
            break
    else:
        # no server listening on (family, sockaddr) found:
        raise ConnError(*lasterr)

    # init errno to errmessage mapping
    # FIXME: should this be only optional?
    owp._init_errcodes()

    if persistent:
        owp = clone(owp, persistent=True)

    # here we should have all connections closed
    assert not isinstance(owp, _PersistentProxy) or owp.conn is None

    return owp
1056060
def attempt_connection(self):
        
        self.connection_error = False
        sleep_exp = 1
        connect_count = 0

        while self.running and self.socket is None and (
            connect_count < self.__reconnect_attempts_max or 
            self.__reconnect_attempts_max == -1 ):
            for host_and_port in self.__host_and_ports:
                try:
                    log.info("Attempting connection to host %s, port %s", host_and_port[0], host_and_port[1])
                    self.socket = get_socket(host_and_port[0], host_and_port[1], self.__timeout)
                    self.__enable_keepalive()
                    need_ssl = self.__need_ssl(host_and_port)

                    if need_ssl:  # wrap socket
                        ssl_params = self.get_ssl(host_and_port)
                        if ssl_params['ca_certs']:
                            cert_validation = ssl.CERT_REQUIRED
                        else:
                            cert_validation = ssl.CERT_NONE
                        try:
                            tls_context = ssl.create_default_context(cafile=ssl_params['ca_certs'])
                        except AttributeError:
                            tls_context = None
                        if tls_context:
                            # Wrap the socket for TLS
                            certfile = ssl_params['cert_file']
                            keyfile = ssl_params['key_file']
                            password = ssl_params.get('password')
                            if certfile and not keyfile:
                                keyfile = certfile
                            if certfile:
                                tls_context.load_cert_chain(certfile, keyfile, password)
                            if cert_validation is None or cert_validation == ssl.CERT_NONE:
                                tls_context.check_hostname = False
                            tls_context.verify_mode = cert_validation
                            self.socket = tls_context.wrap_socket(self.socket, server_hostname=host_and_port[0])
                        else:
                            # Old-style wrap_socket where we don't have a modern SSLContext (so no SNI)
                            self.socket = ssl.wrap_socket(
                                self.socket,
                                keyfile=ssl_params['key_file'],
                                certfile=ssl_params['cert_file'],
                                cert_reqs=cert_validation,
                                ca_certs=ssl_params['ca_certs'],
                                ssl_version=ssl_params['ssl_version'])

                    self.socket.settimeout(self.__timeout)

                    if self.blocking is not None:
                        self.socket.setblocking(self.blocking)

                    #
                    # Validate server cert
                    #
                    if need_ssl and ssl_params['cert_validator']:
                        cert = self.socket.getpeercert()
                        (ok, errmsg) = ssl_params['cert_validator'](cert, host_and_port[0])
                        if not ok:
                            raise SSLError("Server certificate validation failed: %s", errmsg)

                    self.current_host_and_port = host_and_port
                    log.info("Established connection to host %s, port %s", host_and_port[0], host_and_port[1])
                    break
                except socket.error:
                    self.socket = None
                    connect_count += 1
                    log.warning("Could not connect to host %s, port %s", host_and_port[0], host_and_port[1], exc_info=1)

            if self.socket is None:
                sleep_duration = (min(self.__reconnect_sleep_max,
                                      ((self.__reconnect_sleep_initial / (1.0 + self.__reconnect_sleep_increase))
                                       * math.pow(1.0 + self.__reconnect_sleep_increase, sleep_exp)))
                                  * (1.0 + random.random() * self.__reconnect_sleep_jitter))
                sleep_end = monotonic() + sleep_duration
                log.debug("Sleeping for %.1f seconds before attempting reconnect", sleep_duration)
                while self.running and monotonic() < sleep_end:
                    time.sleep(0.2)

                if sleep_duration < self.__reconnect_sleep_max:
                    sleep_exp += 1

        if not self.socket:
            raise exception.ConnectFailedException()
196352
def connect(async = false)
      @connection_thread = Thread.new do
        @connection = TestConnection.new
        @global_channel.dispatch('pusher:connection_established', JSON.dump({'socket_id' => '123abc'}))
      end
      @connection_thread.run
      @connection_thread.join unless async
      return self
    end
995307
def _acquire_connection(self, host, port, use_ssl=False, tunnel=True):
        ''''''
        if hasattr(self._connection_pool, 'acquire_proxy'):
            connection = yield from \
                self._connection_pool.acquire_proxy(host, port, use_ssl,
                                                    tunnel=tunnel)
        else:
            connection = yield from \
                self._connection_pool.acquire(host, port, use_ssl)

        self._connections.add(connection)

        return connection
93260
private Proxy nextProxy() throws IOException {
    if (!hasNextProxy()) {
      throw new SocketException("No route to " + address.url().host()
          + "; exhausted proxy configurations: " + proxies);
    }
    Proxy result = proxies.get(nextProxyIndex++);
    resetNextInetSocketAddress(result);
    return result;
  }
94903
function connect (req, opts, fn) {

  var proxy = this.proxy;

  // create a socket connection to the proxy server
  var socket;
  if (this.secureProxy) {
    socket = tls.connect(proxy);
  } else {
    socket = net.connect(proxy);
  }

  // we need to buffer any HTTP traffic that happens with the proxy before we get
  // the CONNECT response, so that if the response is anything other than an "200"
  // response code, then we can re-play the "data" events on the socket once the
  // HTTP parser is hooked up...
  var buffers = [];
  var buffersLength = 0;

  function read () {
    var b = socket.read();
    if (b) ondata(b);
    else socket.once('readable', read);
  }

  function cleanup () {
    socket.removeListener('data', ondata);
    socket.removeListener('end', onend);
    socket.removeListener('error', onerror);
    socket.removeListener('close', onclose);
    socket.removeListener('readable', read);
  }

  function onclose (err) {
    debug('onclose had error %o', err);
  }

  function onend () {
    debug('onend');
  }

  function onerror (err) {
    cleanup();
    fn(err);
  }

  function ondata (b) {
    buffers.push(b);
    buffersLength += b.length;
    var buffered = Buffer.concat(buffers, buffersLength);
    var str = buffered.toString('ascii');

    if (!~str.indexOf('\r\n\r\n')) {
      // keep buffering
      debug('have not received end of HTTP headers yet...');
      if (socket.read) {
        read();
      } else {
        socket.once('data', ondata);
      }
      return;
    }

    var firstLine = str.substring(0, str.indexOf('\r\n'));
    var statusCode = +firstLine.split(' ')[1];
    debug('got proxy server response: %o', firstLine);

    if (200 == statusCode) {
      // 200 Connected status code!
      var sock = socket;

      // nullify the buffered data since we won't be needing it
      buffers = buffered = null;

      if (opts.secureEndpoint) {
        var host = opts.host;
        // since the proxy is connecting to an SSL server, we have
        // to upgrade this socket connection to an SSL connection
        debug('upgrading proxy-connected socket to TLS connection: %o', opts.host);
        opts.socket = socket;
        opts.servername = opts.host;
        opts.host = null;
        opts.hostname = null;
        opts.port = null;
        sock = tls.connect(opts);
        SocketUtil.secureSocket(sock, host);
      }

      cleanup();
      fn(null, sock);
    } else {
      // some other status code that's not 200... need to re-play the HTTP header
      // "data" events onto the socket once the HTTP machinery is attached so that
      // the user can parse and handle the error status code
      cleanup();

      // save a reference to the concat'd Buffer for the `onsocket` callback
      buffers = buffered;

      // need to wait for the "socket" event to re-play the "data" events
      req.once('socket', onsocket);
      fn(null, socket);
    }
  }

  function onsocket (socket) {
    // replay the "buffers" Buffer onto the `socket`, since at this point
    // the HTTP module machinery has been hooked up for the user
    if ('function' == typeof socket.ondata) {
      // node <= v0.11.3, the `ondata` function is set on the socket
      socket.ondata(buffers, 0, buffers.length);
    } else if (socket.listeners('data').length > 0) {
      // node > v0.11.3, the "data" event is listened for directly
      socket.emit('data', buffers);
    } else {
      // never?
      throw new Error('should not happen...');
    }

    // nullify the cached Buffer instance
    buffers = null;
  }

  socket.on('error', onerror);
  socket.on('close', onclose);
  socket.on('end', onend);

  if (socket.read) {
    read();
  } else {
    socket.once('data', ondata);
  }

  var hostname = opts.host + ':' + opts.port;
  var msg = 'CONNECT ' + hostname + ' HTTP/1.1\r\n';
  var auth = proxy.auth;
  if (auth) {
    msg += 'Proxy-Authorization: Basic ' + Buffer.from(auth, 'utf8').toString('base64') + '\r\n';
  }
  msg += 'Host: ' + hostname + '\r\n' +
      'Connection: close\r\n' +
      '\r\n';
  socket.write(msg);
}
691283
public URLConnection openConnection(URL url) throws IOException {
        Proxy proxy = getProxyFor(url);
        URLConnection conn = null;

        if (proxy != null) {
            conn = url.openConnection(proxy.getProxy());
            proxy.authenticate(conn);
        } else {
            conn = url.openConnection();
        }

        return conn;
    }
726364
async def open(self, port, proxied_path=''):
        
        if not proxied_path.startswith('/'):
            proxied_path = '/' + proxied_path

        client_uri = self.get_client_uri('ws', port, proxied_path)
        headers = self.request.headers

        def message_cb(message):
            """
            Callback when the backend sends messages to us

            We just pass it back to the frontend
            """
            # Websockets support both string (utf-8) and binary data, so let's
            # make sure we signal that appropriately when proxying
            self._record_activity()
            if message is None:
                self.close()
            else:
                self.write_message(message, binary=isinstance(message, bytes))

        def ping_cb(data):
            """
            Callback when the backend sends pings to us.

            We just pass it back to the frontend.
            """
            self._record_activity()
            self.ping(data)

        async def start_websocket_connection():
            self.log.info('Trying to establish websocket connection to {}'.format(client_uri))
            self._record_activity()
            request = httpclient.HTTPRequest(url=client_uri, headers=headers)
            self.ws = await pingable_ws_connect(request=request,
                on_message_callback=message_cb, on_ping_callback=ping_cb)
            self._record_activity()
            self.log.info('Websocket connection established to {}'.format(client_uri))

        ioloop.IOLoop.current().add_callback(start_websocket_connection)
1304088
def _connect(self):
        """"""
        while self.protocol:
            _LOGGER.info('Trying to connect to %s', self.server_address)
            try:
                sock = socket.create_connection(
                    self.server_address, self.reconnect_timeout)
            except socket.timeout:
                _LOGGER.error(
                    'Connecting to socket timed out for %s',
                    self.server_address)
                _LOGGER.info(
                    'Waiting %s secs before trying to connect again',
                    self.reconnect_timeout)
                time.sleep(self.reconnect_timeout)
            except OSError:
                _LOGGER.error(
                    'Failed to connect to socket at %s', self.server_address)
                _LOGGER.info(
                    'Waiting %s secs before trying to connect again',
                    self.reconnect_timeout)
                time.sleep(self.reconnect_timeout)
            else:
                self.tcp_check_timer = time.time()
                self.tcp_disconnect_timer = time.time()
                transport = TCPTransport(
                    sock, lambda: self.protocol, self._check_connection)
                poll_thread = threading.Thread(target=self._poll_queue)
                self._stop_event.clear()
                poll_thread.start()
                transport.start()
                transport.connect()
                return