Equivalent to socket.connect(), but sends an client handshake request
        after connecting.

        `address` is a (host, port) tuple of the server to connect to.
426553
def connect(self, address):
        
        self.sock.connect(address)
        ClientHandshake(self).perform()
        self.handshake_sent = True
377377
def send(self, message):
        
        self.socket.sendto(message.SerializeToString(), self.address)
        return None
1334642
def receive_connection():
    
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("localhost", 8080))
    server.listen(1)
    client = server.accept()[0]
    server.close()
    return client
177507
def open(self, host, port=0):
        
        self.eof = 0
        if not port:
            port = TELNET_PORT
        self.host = host
        self.port = port
        msg = "getaddrinfo returns an empty list"
        for res in socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.sock = socket.socket(af, socktype, proto)
                self.sock.settimeout(self.connect_timeout)
                self.sock.connect(sa)
            except socket.error as msg_:
                msg = '{} => telnet://{}:{}'.format(msg_, host, port)
                if self.sock:
                    self.sock.close()
                self.sock = None
                continue
            break
        if not self.sock:
            raise socket.error(msg)
206589
def serve(socket)
      header = read_header(socket)
      # not documented protocol?
      if header['probe'] == '1'
        write_header(socket, build_header)
      elsif check_header(header)
        write_header(socket, build_header)
        read_and_callback(socket)
        if header['persistent'] == '1'
          loop do
            read_and_callback(socket)
          end
        end
      else
        socket.close
        raise 'header check error'
      end
    end
7834
def accept(self):
        
        sock, address = self.sock.accept()
        wsock = websocket(sock)
        wsock.secure = self.secure
        ServerHandshake(wsock).perform(self)
        wsock.handshake_sent = True
        return wsock, address
1012943
def get_socket(self, address, role):
        
        #
        # If this thread doesn't yet have a sockets cache
        # in its local storage, create one here.
        #
        try:
            self._tls.sockets
        except AttributeError:
            self._tls.sockets = {}
        
        # Convert the address to a single canonical string.
        #
        # If a list of addresses is passed, turn it into a tuple
        # of canonical addresses for use as a dictionary key. 
        # Otherwise convert it to a single canonical string.
        #
        if isinstance(address, list):
            caddress = tuple(core.address(a) for a in address)
        else:
            caddress = core.address(address)
            
        #
        # Each socket is identified for this thread by its address(es)
        # and the role the socket is playing (listener, publisher, etc.)
        # That is, within one thread, we are cacheing a read or a write
        # socket to the same address(es).
        #
        # The slight corner case from this is that if you attempt to
        # send to [addressA, addressB] and then to addressA and then
        # to [addressB, addressA], three separate sockets will be
        # created and used.
        #
        identifier = caddress
        
        if identifier not in self._tls.sockets:
            _logger.debug("%s does not exist in local sockets", identifier)
            #
            # If this is a listening / subscribing socket, it can only
            # be bound once, regardless of thread. Therefore keep a
            # threads-global list of addresses used and make sure this
            # one hasn't been used elsewhere.
            #
            if role in Socket.binding_roles:
                with self._lock:
                    if identifier in self._sockets:
                        raise core.SocketAlreadyExistsError("You cannot create a listening socket in more than one thread")
                    else:
                        self._sockets.add(identifier)
            
            type = self.roles[role]
            socket = context.socket(type)
            socket.role = role
            socket.address = caddress
            #
            # Do this last so that an exception earlier will result
            # in the socket not being cached
            #
            self._tls.sockets[identifier] = socket
        else:
            _logger.debug("%s already not exist in local sockets", identifier)
            #
            # Only return sockets created in this thread
            #
            socket = self._tls.sockets[identifier]

        return socket
920477
def _connect(self, address):
        

        latency = 0
        conn_interval_min = 6
        conn_interval_max = 100
        timeout = 1.0

        try:
            #Allow passing either a binary address or a hex string
            if isinstance(address, str) and len(address) > 6:
                address = address.replace(':', '')
                address = bytes(bytearray.fromhex(address)[::-1])
        except ValueError:
            return False, None

        #Allow simple determination of whether a device has a public or private address
        #This is not foolproof
        private_bits = bytearray(address)[-1] >> 6
        if private_bits == 0b11:
            address_type = 1
        else:
            address_type = 0

        payload = struct.pack("<6sBHHHH", address, address_type, conn_interval_min,
                              conn_interval_max, int(timeout*100.0), latency)
        response = self._send_command(6, 3, payload)

        result, handle = unpack("<HB", response.payload)
        if result != 0:
            return False, None

        #Now wait for the connection event that says we connected or kill the attempt after timeout
        def conn_succeeded(event):
            if event.command_class == 3 and event.command == 0:
                event_handle, = unpack("B", event.payload[0:1])
                return event_handle == handle

        #FIXME Hardcoded timeout
        events = self._wait_process_events(4.0, lambda x: False, conn_succeeded)
        if len(events) != 1:
            self._stop_scan()
            return False, None

        handle, _, addr, _, interval, timeout, latency, _ = unpack("<BB6sBHHHB", events[0].payload)
        formatted_addr = ":".join(["%02X" % x for x in bytearray(addr)])
        self._logger.info('Connected to device %s with interval=%d, timeout=%d, latency=%d',
                          formatted_addr, interval, timeout, latency)

        connection = {"handle": handle}
        return True, connection
435319
def send(self, data):
        
        sock = socket.socket(*self.sock_args)
        try:
            sock.connect(self.sock_addr)
        except socket.error as exc:
            raise socket.error("Can't connect to %r (%s)" % (self.url.geturl(), exc))

        try:
            # Send request
            sock.send(data)

            # Read response
            while True:
                chunk = sock.recv(self.CHUNK_SIZE)
                if chunk:
                    yield chunk
                else:
                    break
        finally:
            # Clean up
            sock.close()
530281
def connect(self, ip, port):
        
        _check_valid_port_range(port)

        address = (ip, port)

        if address in self._addresses:
            error = 'Already connected to {0} on port {1}'.format(ip, port)
            log.exception(error)
            raise ValueError(error)

        self._addresses.append(address)

        if self._is_ready:
            _check_valid_num_connections(self._sock.socket_type,
                                         len(self._addresses))

            _connect_zmq_sock(self._sock, ip, port)

        return self
992576
private static ChannelFuture socksConnect(Channel channel, InetSocketAddress remoteAddress)
    {
        channel.write(createHandshake(remoteAddress));
        return ((Socks4HandshakeHandler) channel.getPipeline().get("handshake")).getChannelFuture();
    }
106312
def connection_made(self, address):
        """"""
        self._proxy = PickleProxy(self.loop, self)
        for d in self._proxy_deferreds:
            d.callback(self._proxy)
865659
public Socket connectSocket(
        final Socket sock,
        final String host,
        final int port,
        final InetAddress localAddress,
        int localPort,
        final HttpParams params
    ) throws IOException {

        if (host == null) {
            throw new IllegalArgumentException("Target host may not be null.");
        }
        if (params == null) {
            throw new IllegalArgumentException("Parameters may not be null.");
        }

        SSLSocket sslsock = (SSLSocket)
            ((sock != null) ? sock : createSocket());

        if ((localAddress != null) || (localPort > 0)) {

            // we need to bind explicitly
            if (localPort < 0)
                localPort = 0; // indicates "any"

            InetSocketAddress isa =
                new InetSocketAddress(localAddress, localPort);
            sslsock.bind(isa);
        }

        int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
        int soTimeout = HttpConnectionParams.getSoTimeout(params);

        InetSocketAddress remoteAddress;
        if (this.nameResolver != null) {
            remoteAddress = new InetSocketAddress(this.nameResolver.resolve(host), port); 
        } else {
            remoteAddress = new InetSocketAddress(host, port);            
        }
        
        sslsock.connect(remoteAddress, connTimeout);

        sslsock.setSoTimeout(soTimeout);
        try {
            hostnameVerifier.verify(host, sslsock);
            // verifyHostName() didn't blowup - good!
        } catch (IOException iox) {
            // close the socket before re-throwing the exception
            try { sslsock.close(); } catch (Exception x) { /*ignore*/ }
            throw iox;
        }

        return sslsock;
    }
1017590
def listen(self, address, ssl=False, family=0, flags=0, ipc=False, backlog=128):
        
        handles = []
        handle_args = ()
        if isinstance(address, six.string_types):
            handle_type = pyuv.Pipe
            handle_args = (ipc,)
            addresses = [address]
        elif isinstance(address, tuple):
            handle_type = pyuv.TCP
            result = getaddrinfo(address[0], address[1], family, socket.SOCK_STREAM,
                                 socket.IPPROTO_TCP, flags)
            addresses = [res[4] for res in result]
        elif isinstance(address, pyuv.Stream):
            handles.append(address)
            addresses = []
        else:
            raise TypeError('expecting a string, tuple or pyuv.Stream')
        for addr in addresses:
            handle = handle_type(self._hub.loop, *handle_args)
            try:
                if compat.pyuv_pipe_helper(handle, handle_args, 'bind', addr):
                    handles.append(handle)
                    break
                handle.bind(addr)
            except pyuv.error.UVError as e:
                self._log.warning('bind error {!r}, skipping {}', e[0], saddr(addr))
                continue
            handles.append(handle)
        addresses = []
        for handle in handles:
            if backlog is not None:
                callback = functools.partial(self._on_new_connection, ssl=ssl)
                handle.listen(callback, backlog)
                addr = handle.getsockname()
                self._log.debug('listen on {}', saddr(addr))
            addresses.append(addr)
        self._handles += handles
        self._addresses += addresses
1080736
def connect(self, dest_pair):
        
        if len(dest_pair) != 2 or dest_pair[0].startswith("["):
            # Probably IPv6, not supported -- raise an error, and hope
            # Happy Eyeballs (RFC6555) makes sure at least the IPv4
            # connection works...
            raise socket.error("PySocks doesn't support IPv6: %s" % str(dest_pair))

        dest_addr, dest_port = dest_pair

        if self.type == socket.SOCK_DGRAM:
            if not self._proxyconn:
                self.bind(("", 0))
            dest_addr = socket.gethostbyname(dest_addr)

            # If the host address is INADDR_ANY or similar, reset the peer
            # address so that packets are received from any peer
            if dest_addr == "0.0.0.0" and not dest_port:
                self.proxy_peername = None
            else:
                self.proxy_peername = (dest_addr, dest_port)
            return

        proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy

        # Do a minimal input check first
        if (not isinstance(dest_pair, (list, tuple))
                or len(dest_pair) != 2
                or not dest_addr
                or not isinstance(dest_port, int)):
            raise GeneralProxyError("Invalid destination-connection (host, port) pair")


        # We set the timeout here so that we don't hang in connection or during
        # negotiation.
        super(socksocket, self).settimeout(self._timeout)

        if proxy_type is None:
            # Treat like regular socket object
            self.proxy_peername = dest_pair
            super(socksocket, self).settimeout(self._timeout)
            super(socksocket, self).connect((dest_addr, dest_port))
            return

        proxy_addr = self._proxy_addr()

        try:
            # Initial connection to proxy server.
            super(socksocket, self).connect(proxy_addr)

        except socket.error as error:
            # Error while connecting to proxy
            self.close()
            proxy_addr, proxy_port = proxy_addr
            proxy_server = "{0}:{1}".format(proxy_addr, proxy_port)
            printable_type = PRINTABLE_PROXY_TYPES[proxy_type]

            msg = "Error connecting to {0} proxy {1}".format(printable_type,
                                                           proxy_server)
            log.debug("%s due to: %s", msg, error)
            raise ProxyConnectionError(msg, error)

        else:
            # Connected to proxy server, now negotiate
            try:
                # Calls negotiate_{SOCKS4, SOCKS5, HTTP}
                negotiate = self._proxy_negotiators[proxy_type]
                negotiate(self, dest_addr, dest_port)
            except socket.error as error:
                # Wrap socket errors
                self.close()
                raise GeneralProxyError("Socket error", error)
            except ProxyError:
                # Protocol error while negotiating with proxy
                self.close()
                raise
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;
    }
205208
def send_proxy_connect_request(req)
      return unless req.uri.https? && req.using_proxy?

      @pending_request = true

      req.connect_using_proxy @socket

      @pending_request  = false
      @pending_response = true

      read_headers!
      @proxy_response_headers = @parser.headers

      if @parser.status_code != 200
        @failed_proxy_connect = true
        return
      end

      @parser.reset
      @pending_response = false
    end