connects to server
334952
function connect()
    {
        if(scope._conn)
        {
            if(scope._conn.readyState === 1)
            {
                return;
            }
            scope._conn.close();
        }
        var url = (scope._redirectURL.length>0) ? scope._redirectURL : scope._url;

        scope._conn            = new WebSocket(url);
        scope._conn.binaryType = "arraybuffer";
        scope._conn.open       = onOpen;
        scope._conn.onerror    = onerror;
        scope._conn.onclose    = onClose;
        scope._conn.onmessage  = onMessage;
    }
956966
function connect () {
  // connection
  if (!alreadyConnectedOnce) {
    if (connectedPromise === null) connection = createConnection()
    var url = AppConfig.apiUrl + 'websocket/chat'
    if (accessToken) {
      token = accessToken
      url += '?access_token=' + accessToken
    }
    socket = new SockJS(url)
    stompClient = webstomp.over(socket)
    // stompClient.debug = null
    console.tron.log(`Connecting to ${url}`)
    var headers = {}
    stompClient.connect(headers, onConnect, onError)
    alreadyConnectedOnce = true
  }
}
599868
def connect(self):
        """"""
        log.info('Connecting socket on %s:%d' % (self.server, self.port))
        tries = 0
        while not self._socket and tries < 10:
            try:
                time.sleep(.2 * tries)
                self._socket = Socket((self.server, self.port))
            except socket.error:
                tries += 1
                log.warning(
                    'You must start/install wdb.server '
                    '(Retrying on %s:%d) [Try #%d/10]' %
                    (self.server, self.port, tries)
                )
                self._socket = None

        if not self._socket:
            log.warning('Could not connect to server')
            return

        Wdb._sockets.append(self._socket)
        self._socket.send_bytes(self.uuid.encode('utf-8'))
686484
function _connect()
    {
        $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->connectionTimeout);
        if (!$this->fsock) {
            user_error(rtrim("Cannot connect to {$this->host}:{$this->port}. Error $errno. $errstr"));
            return false;
        }

        $this->server_identification = $init_line = fgets($this->fsock, 255);

        if (defined('NET_SSH1_LOGGING')) {
            $this->_append_log('<-', $this->server_identification);
            $this->_append_log('->', $this->identifier . "\r\n");
        }

        if (!preg_match('#SSH-([0-9\.]+)-(.+)#', $init_line, $parts)) {
            user_error('Can only connect to SSH servers');
            return false;
        }
        if ($parts[1][0] != 1) {
            user_error("Cannot connect to SSH $parts[1] servers");
            return false;
        }

        fputs($this->fsock, $this->identifier."\r\n");

        $response = $this->_get_binary_packet();
        if ($response[self::RESPONSE_TYPE] != NET_SSH1_SMSG_PUBLIC_KEY) {
            user_error('Expected SSH_SMSG_PUBLIC_KEY');
            return false;
        }

        $anti_spoofing_cookie = $this->_string_shift($response[self::RESPONSE_DATA], 8);

        $this->_string_shift($response[self::RESPONSE_DATA], 4);

        if (strlen($response[self::RESPONSE_DATA]) < 2) {
            return false;
        }
        $temp = unpack('nlen', $this->_string_shift($response[self::RESPONSE_DATA], 2));
        $server_key_public_exponent = new BigInteger($this->_string_shift($response[self::RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
        $this->server_key_public_exponent = $server_key_public_exponent;

        if (strlen($response[self::RESPONSE_DATA]) < 2) {
            return false;
        }
        $temp = unpack('nlen', $this->_string_shift($response[self::RESPONSE_DATA], 2));
        $server_key_public_modulus = new BigInteger($this->_string_shift($response[self::RESPONSE_DATA], ceil($temp['len'] / 8)), 256);

        $this->server_key_public_modulus = $server_key_public_modulus;

        $this->_string_shift($response[self::RESPONSE_DATA], 4);

        if (strlen($response[self::RESPONSE_DATA]) < 2) {
            return false;
        }
        $temp = unpack('nlen', $this->_string_shift($response[self::RESPONSE_DATA], 2));
        $host_key_public_exponent = new BigInteger($this->_string_shift($response[self::RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
        $this->host_key_public_exponent = $host_key_public_exponent;

        if (strlen($response[self::RESPONSE_DATA]) < 2) {
            return false;
        }
        $temp = unpack('nlen', $this->_string_shift($response[self::RESPONSE_DATA], 2));
        $host_key_public_modulus = new BigInteger($this->_string_shift($response[self::RESPONSE_DATA], ceil($temp['len'] / 8)), 256);

        $this->host_key_public_modulus = $host_key_public_modulus;

        $this->_string_shift($response[self::RESPONSE_DATA], 4);

        // get a list of the supported ciphers
        if (strlen($response[self::RESPONSE_DATA]) < 4) {
            return false;
        }
        extract(unpack('Nsupported_ciphers_mask', $this->_string_shift($response[self::RESPONSE_DATA], 4)));

        foreach ($this->supported_ciphers as $mask => $name) {
            if (($supported_ciphers_mask & (1 << $mask)) == 0) {
                unset($this->supported_ciphers[$mask]);
            }
        }

        // get a list of the supported authentications
        if (strlen($response[self::RESPONSE_DATA]) < 4) {
            return false;
        }
        extract(unpack('Nsupported_authentications_mask', $this->_string_shift($response[self::RESPONSE_DATA], 4)));
        foreach ($this->supported_authentications as $mask => $name) {
            if (($supported_authentications_mask & (1 << $mask)) == 0) {
                unset($this->supported_authentications[$mask]);
            }
        }

        $session_id = pack('H*', md5($host_key_public_modulus->toBytes() . $server_key_public_modulus->toBytes() . $anti_spoofing_cookie));

        $session_key = Random::string(32);
        $double_encrypted_session_key = $session_key ^ str_pad($session_id, 32, chr(0));

        if ($server_key_public_modulus->compare($host_key_public_modulus) < 0) {
            $double_encrypted_session_key = $this->_rsa_crypt(
                $double_encrypted_session_key,
                array(
                    $server_key_public_exponent,
                    $server_key_public_modulus
                )
            );
            $double_encrypted_session_key = $this->_rsa_crypt(
                $double_encrypted_session_key,
                array(
                    $host_key_public_exponent,
                    $host_key_public_modulus
                )
            );
        } else {
            $double_encrypted_session_key = $this->_rsa_crypt(
                $double_encrypted_session_key,
                array(
                    $host_key_public_exponent,
                    $host_key_public_modulus
                )
            );
            $double_encrypted_session_key = $this->_rsa_crypt(
                $double_encrypted_session_key,
                array(
                    $server_key_public_exponent,
                    $server_key_public_modulus
                )
            );
        }

        $cipher = isset($this->supported_ciphers[$this->cipher]) ? $this->cipher : self::CIPHER_3DES;
        $data = pack('C2a*na*N', NET_SSH1_CMSG_SESSION_KEY, $cipher, $anti_spoofing_cookie, 8 * strlen($double_encrypted_session_key), $double_encrypted_session_key, 0);

        if (!$this->_send_binary_packet($data)) {
            user_error('Error sending SSH_CMSG_SESSION_KEY');
            return false;
        }

        switch ($cipher) {
            //case self::CIPHER_NONE:
            //    $this->crypto = new \phpseclib\Crypt\Null();
            //    break;
            case self::CIPHER_DES:
                $this->crypto = new DES();
                $this->crypto->disablePadding();
                $this->crypto->enableContinuousBuffer();
                $this->crypto->setKey(substr($session_key, 0,  8));
                break;
            case self::CIPHER_3DES:
                $this->crypto = new TripleDES(TripleDES::MODE_3CBC);
                $this->crypto->disablePadding();
                $this->crypto->enableContinuousBuffer();
                $this->crypto->setKey(substr($session_key, 0, 24));
                break;
            //case self::CIPHER_RC4:
            //    $this->crypto = new RC4();
            //    $this->crypto->enableContinuousBuffer();
            //    $this->crypto->setKey(substr($session_key, 0,  16));
            //    break;
        }

        $response = $this->_get_binary_packet();

        if ($response[self::RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) {
            user_error('Expected SSH_SMSG_SUCCESS');
            return false;
        }

        $this->bitmap = self::MASK_CONNECTED;

        return true;
    }
1230271
function () {

	if (l_ip_port === undefined) {
		LOG.warn('not init (or already disposed), cannot connect to server');
		return;
	}

	if (l_connector === undefined)    
		l_connector = new SR.Connector(l_config);

    // establish connection
	LOG.warn('connecting to: ' + l_ip_port);
	l_connector.connect(l_ip_port, function (err, socket) {
		
		if (err) {
			// try-again later
			LOG.warn('attempt to re-connect in: ' + l_timeoutConnectRetry + 'ms');
			setTimeout(l_connect, l_timeoutConnectRetry);
			return;
		}
				
		LOG.warn('connection to: ' + socket.host + ':' + socket.port + ' established');
        l_connector.send('SR_REGISTER_SERVER', l_para, 'SR_REGISTER_SERVER_R', function (res) {
            console.log(res.data);
        });
	});    
}
1206267
public function connect()
    {
        /*
         The Server MUST process a second CONNECT Packet sent from a Client as a protocol violation
         and disconnect the Client [MQTT-3.1.0-2]

         So CONNECT SHOULD be a blocking connection.
         */
        $this->socket->connect(function ($cli) {
            Debug::Log(Debug::INFO, 'connect(): Connection established.');
            /**
             * @var Message\CONNECT $connectobj
             */
            $connectobj = $this->getMessageObject(Message::CONNECT);

            if (!$this->connect_clean && empty($this->clientid)) {
                throw new Exception('Client id must be provided if Clean Session flag is set false.');
            }

            # default client id
            if (empty($this->clientid)) {
                $this->clientid = 'mqtt' . substr(md5(uniqid('mqtt', true)), 8, 16);
            } else {
                $connectobj->setClientId($this->clientid);
            }
            Debug::Log(Debug::DEBUG, 'connect(): clientid=' . $this->clientid);

            $connectobj->setKeepalive($this->keepalive);
            Debug::Log(Debug::DEBUG, 'connect(): keepalive=' . $this->keepalive);

            $connectobj->setAuth($this->username, $this->password);
            Debug::Log(Debug::DEBUG, 'connect(): username=' . $this->username . ' password=' . $this->password);

            $connectobj->setClean($this->connect_clean);

            if ($this->connect_will instanceof Will) {
                $connectobj->setWill($this->connect_will);
            }

            $length = 0;

            $bytes_written = $this->message_write($connectobj, $length);
            Debug::Log(Debug::DEBUG, 'connect(): bytes written=' . $bytes_written);

            $this->keepalive_time = swoole_timer_tick($this->keepalive * 500, [$this, 'keepalive']);
        }, [$this, 'onReceive'],function (){
            secho("MQTT", "连接mqtt服务器失败,正在重试");
            swoole_timer_after(1000,[$this,'connect']);
        },function (){
            if ($this->keepalive_time!=null) {
                swoole_timer_clear($this->keepalive_time);
                $this->keepalive_time = null;
            }
            $this->connect();
        });
    }
1175162
def connect(self):
        """"""
        logger.debug("Opening connection to %s:%s", self.url.hostname, self.url.port)
        try:
            self.connection = httplib.HTTPConnection(self.url.hostname, self.url.port)
            self.connection.connect()
        except (httplib.HTTPException, socket.error) as e:
            raise errors.InterfaceError('Unable to connect to the specified service', e)
357278
function Server(/* [options], [connectionListener] */) {
    events.EventEmitter.call(this);
    var self = this;

    var options;
    if (typeof arguments[0] === 'function') {
        options = {};
        this.on('connection', arguments[0]);
    } else {
        options = arguments[0] || {};
        if (typeof arguments[1] === 'function') {
            this.on('connection', arguments[1]);
        }
    }

    this._server = net.createServer(options, this._handler.bind(this));
    this._server.on('listening', function () {
        self.emit('listening');
    })
    this._server.on('close', function () {
        self.emit('close');
    })
    this._server.on('error', function (e) {
        self.emit('error', e);
    });
}
408400
def connect(self, *args, auto_reconnect=False, **kwargs):
        
        connection_info = {
            'auto_reconnect': auto_reconnect,
            'args': args,
            'kwargs': kwargs,
        }
        self.connect_info['connection'] = connection_info

        # confirm we have user info set
        if 'user' not in self.connect_info:
            raise Exception('`set_user_info` must be called before connecting to server.')

        # create connection and run
        connection = loop.create_connection(lambda: self,
                                            *args, **kwargs)
        asyncio.Task(connection)
1144874
def _connect(self):
        """"""
        while self.protocol:
            _LOGGER.info('Trying to connect to %s', self.port)
            try:
                ser = serial.serial_for_url(
                    self.port, self.baud, timeout=self.timeout)
            except serial.SerialException:
                _LOGGER.error('Unable to connect to %s', self.port)
                _LOGGER.info(
                    'Waiting %s secs before trying to connect again',
                    self.reconnect_timeout)
                time.sleep(self.reconnect_timeout)
            else:
                transport = serial.threaded.ReaderThread(
                    ser, lambda: self.protocol)
                transport.daemon = False
                poll_thread = threading.Thread(target=self._poll_queue)
                self._stop_event.clear()
                poll_thread.start()
                transport.start()
                transport.connect()
                return
413392
protected function connect()
    {
        if (!is_object(self::$instance)) {
            self::$instance = new \Memcached();

            if (!empty($this->options['option'])) {
                self::$instance->setOptions($this->options['option']);
            }

            // Set connection timeout ms
            if ($this->options['timeout'] > 0) {
                self::$instance->setOption(\Memcached::OPT_CONNECT_TIMEOUT, $this->options['timeout']);
            }

            // Cluster connections
            $hosts = explode(',', $this->options['host']);
            $ports = explode(',', $this->options['port']);
            if (empty($ports[0])) {
                $ports[0] = 11211;
            }

            // connection establishment
            $servers = [];
            foreach ((array) $hosts as $i => $host) {
                $servers[] = [$host, (isset($ports[$i]) ? $ports[$i] : $ports[0]), 1];
            }

            self::$instance->addServers($servers);

            if ('' != $this->options['username']) {
                self::$instance->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
                self::$instance->setSaslAuthData($this->options['username'], $this->options['password']);
            }
        }
    }
1095617
protected function connect()
    {
        if (!empty($this->conn)) {
            return;
        }

        if (!extension_loaded('ssh2')) {
            throw new ServerException(
                "Unable to initialize sftp storage server, extension 'ssh2' not found"
            );
        }

        $session = ssh2_connect(
            $this->options['host'],
            $this->options['port'],
            $this->options['methods']
        );

        if (empty($session)) {
            throw new ServerException(
                "Unable to connect to remote SSH server '{$this->options['host']}'"
            );
        }

        //Authorization
        switch ($this->options['authMethod']) {
            case self::NONE:
                ssh2_auth_none($session, $this->options['username']);
                break;

            case self::PASSWORD:
                ssh2_auth_password(
                    $session,
                    $this->options['username'],
                    $this->options['password']
                );
                break;

            case self::PUB_KEY:
                ssh2_auth_pubkey_file(
                    $session,
                    $this->options['username'],
                    $this->options['publicKey'],
                    $this->options['privateKey'],
                    $this->options['secret']
                );
                break;
        }

        $this->conn = ssh2_sftp($session);
    }
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))
399976
protected function connect()
    {
        $this->socket = new Net_Notifier_Socket_Client(
            sprintf(
                'tcp://%s:%s',
                $this->host,
                $this->port
            ),
            $this->timeout / 1000
        );

        $this->connection = new Net_Notifier_WebSocket_Connection(
            $this->socket
        );

        $this->connection->startHandshake(
            $this->host,
            $this->port,
            $this->resource,
            array(Net_Notifier_WebSocket::PROTOCOL)
        );

        // read handshake response
        $state = $this->connection->getState();
        while ($state < Net_Notifier_WebSocket_Connection::STATE_OPEN) {

            $read = array($this->socket->getRawSocket());

            $result = stream_select(
                $read,
                $write = null,
                $except = null,
                null
            );

            if ($result === 1) {
                $this->connection->read(self::READ_BUFFER_LENGTH);
            }

            $state = $this->connection->getState();
        }
    }
91658
def connectToServer(self):
    """"""
    self.rtspSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
      self.rtspSocket.connect((self.serverAddr, self.serverPort))
    except:
      tkMessageBox.showwarning('Connection Failed', 'Connection to \'%s\' failed.' %self.serverAddr)
1204832
def connect(self):
        """"""
        super(TLSTransport, self).connect()
        self.socket = ssl.wrap_socket(
            self.socket,
            ssl_version=ssl.PROTOCOL_TLSv1,
            cert_reqs=ssl.CERT_REQUIRED,
            ca_certs=self.ca_certs)
171313
function connection(socket, server) {
  var conn = new Connection(socket)
    , tcp = (server instanceof TcpServer);

  var maxclients = this.conf.get(ConfigKey.MAXCLIENTS);
  if(maxclients && (this.state.length + 1 > maxclients)) {

    this.state.emit('rejected', conn.client.addr, maxclients);

    this.log.debug('rejected %s, exceeds maxclients %s',
      conn.client.addr, maxclients);

    function onWrite() {
      socket.end();
    }

    return conn.write(MaxClients, onWrite.bind(this));
  }

  if(tcp) {
    this.log.debug('accepted connection from %s', conn.client.addr);
  }else if(server) {
    this.log.debug('accepted connection to %s', server.name);
  }else if(!server) {
    this.log.debug('accepted connection in %s', process.pid);
  }

  var timeout = this.conf.get(ConfigKey.TIMEOUT);
  if(typeof timeout === 'number' && timeout) {
    this.log.debug('setting idle timeout for client #%s to %ss',
      conn.id, timeout);
    // config is seconds, socket want milliseconds
    socket.setTimeout(timeout * 1000, function onTimeout() {
      // TODO: log client connection timeout
      socket.destroy();
    })
  }

  conn.once('disconnect', this.disconnect.bind(this));
  conn.on('command', this.command);
  this._state.addConnection(conn);
}