Connect to global server.
@throws \Exception
497452
protected function getConnection($key)
    {
        $offset = crc32($key) % count($this->_globalServers);
        if ($offset < 0) {
            $offset = -$offset;
        }

        if (!isset($this->_globalConnections[$offset]) || feof($this->_globalConnections[$offset])) {
            $connection = stream_socket_client("tcp://{$this->_globalServers[$offset]}", $code, $msg, $this->timeout);
            if (!$connection) {
                throw new \Exception($msg);
            }
            stream_set_timeout($connection, $this->timeout);
            if (class_exists('\Workerman\Lib\Timer') && php_sapi_name() === 'cli') {
                $timer_id = \Workerman\Lib\Timer::add($this->pingInterval, function ($connection) use (&$timer_id) {
                    $buffer = pack('N', 8) . "ping";
                    if (strlen($buffer) !== @fwrite($connection, $buffer)) {
                        @fclose($connection);
                        \Workerman\Lib\Timer::del($timer_id);
                    }
                }, array($connection));
            }
            $this->_globalConnections[$offset] = $connection;
        }
        return $this->_globalConnections[$offset];
    }
458940
private function connect()
    {
        // validate connection parameters
        if (!$this->config['wrapper']
            || !$this->config['user']
                || !$this->config['password']
                    || !$this->config['table']) {

            throw new \Exception('Insufficient connection parameters');
        }

        // try to connect
        try {
            $handle = new \PDO(
                $this->config['wrapper'],
                $this->config['user'],
                $this->config['password']
            );
            $handle->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);

        } catch (\PDOException $e) {
            throw new \PDOException('PDOException: ' . $e->getMessage());
        }

        return $handle;
    }
1178210
public function connect()
    {
        try {
            $this->pdo = new \PDO(
                $this->datasource->getDsn(),
                $this->datasource->getUser(),
                $this->datasource->getPassword(),
                $this->datasource->getOption()
            );
            return true;
        } catch (PDOException $e) {
            throw new \Exception($e->getMessage());
            return false;
        }
    }
881710
private function connect()
        {
            $this->fd = fsockopen($this->serverHost, $this->serverPort, $errno, $errstr);

            if (!$this->fd) {
                throw new Exception('fsockopen returned: '.$errstr);
            }

            $key = $this->generateKey();

            $out  = "GET " . $this->serverPath . "/websocket/" . $this->session['sid'] . " HTTP/1.1\r\n";
            $out .= "Host: " . $this->serverHost . "\r\n";
            $out .= "Upgrade: WebSocket\r\n";
            $out .= "Connection: Upgrade\r\n";
            $out .= "Sec-WebSocket-Key: " . $key . "\r\n";
            $out .= "Sec-WebSocket-Version: 13\r\n";
            $out .= "Origin: *\r\n\r\n";

            fwrite($this->fd, $out);

            $res = fgets($this->fd);

            if ($res === false) {
                throw new Exception('Socket.io did not respond properly. Aborting...');
            }

            if ($subres = substr($res, 0, 12) != 'HTTP/1.1 101') {
                throw new Exception('Unexpected Response. Expected HTTP/1.1 101 got '.$subres.'. Aborting...');
            }

            while(true) {
                $res = trim(fgets($this->fd));
                if ($res === '') break;
            }

            if ($this->read) {
                if ($this->read() != '1::') {
                    throw new Exception('Socket.io did not send connect response. Aborting...');
                } else {
                    $this->stdout('info', 'Server report us as connected !');
                }
            }

            $this->heartbeatStamp = time();
        }
857376
private function connect () {
    $connectionString = "host=".$this->server." port=".$this->port." dbname=".$this->db." user=".$this->user." password=".$this->password;
    $this->handler = pg_connect ($connectionString);
  }
259890
public function connect(): self
    {
        $this->logger->debug('connect to ldap server ['.$this->uri.']', [
            'category' => get_class($this),
        ]);

        if (null === $this->binddn) {
            $this->logger->warning('no binddn set for ldap connection, you should avoid anonymous bind', [
                'category' => get_class($this),
            ]);
        }

        if (false === $this->tls && 'ldaps' !== substr($this->uri, 0, 5)) {
            $this->logger->warning('neither tls nor ldaps enabled for ldap connection, it is strongly reccommended to encrypt ldap connections', [
                'category' => get_class($this),
            ]);
        }

        $this->connection = ldap_connect($this->uri);

        foreach ($this->options as $opt => $value) {
            ldap_set_option($this->connection, constant($opt), $value);
        }

        if (true === $this->tls) {
            ldap_start_tls($this->connection);
        }

        if ($this->connection) {
            if (null !== $this->binddn) {
                $bind = ldap_bind($this->connection, $this->binddn, $this->bindpw);

                if ($bind) {
                    $this->logger->info('bind to ldap server ['.$this->uri.'] with binddn ['.$this->binddn.'] was succesful', [
                        'category' => get_class($this),
                    ]);

                    return $this;
                }

                throw new Exception('failed bind to ldap server, error: '.ldap_error($this->connection));
            }
        } else {
            throw new Exception('failed connect to ldap server '.$this->uri);
        }

        return $this;
    }
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);
    }
540503
public function connect()
    {
        if ($this->ssl) {
            $this->connection = ftp_ssl_connect($this->getHost(), $this->getPort(), $this->getTimeout());
        } else {
            $this->connection = ftp_connect($this->getHost(), $this->getPort(), $this->getTimeout());
        }

        if ( ! $this->connection) {
            throw new RuntimeException('Could not connect to host: ' . $this->getHost() . ', port:' . $this->getPort());
        }

        $this->login();
        $this->setUtf8Mode();
        $this->setConnectionPassiveMode();
        $this->setConnectionRoot();
        $this->isPureFtpd = $this->isPureFtpdServer();
    }
28381
protected function connect()
    {
        if (!empty($this->conn)) {
            return;
        }

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

        $conn = ftp_connect(
            $this->options['host'],
            $this->options['port'],
            $this->options['timeout']
        );

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

        if (!ftp_login($conn, $this->options['username'], $this->options['password'])) {
            throw new ServerException(
                "Unable to authorize on remote FTP server '{$this->options['host']}'"
            );
        }

        if (!ftp_pasv($conn, $this->options['passive'])) {
            throw new ServerException(
                "Unable to set passive mode at remote FTP server '{$this->options['host']}'"
            );
        }

        $this->conn = $conn;
    }
665372
private function connect()
    {
        $headers = [];
        if ($this->lastId) {
            $headers['Last-Event-ID'] = $this->lastId;
        }

        $this->response = $this->client->request('GET', $this->url, [
            'stream' => true,
            'headers' => $headers,
        ]);

        if ($this->response->getStatusCode() == 204) {
            throw new RuntimeException('Server forbid connection retry by responding 204 status code.');
        }
    }
1142519
public function listen()
    {
        if (!$this->_socketName) {
            return;
        }

        // Autoload.
        Autoloader::setRootPath($this->_autoloadRootPath);

        if (!$this->_mainSocket) {
            // Get the application layer communication protocol and listening address.
            list($scheme, $address) = explode(':', $this->_socketName, 2);
            // Check application layer protocol class.
            if (!isset(static::$_builtinTransports[$scheme])) {
                $scheme         = ucfirst($scheme);
                $this->protocol = substr($scheme,0,1)==='\\' ? $scheme : '\\Protocols\\' . $scheme;
                if (!class_exists($this->protocol)) {
                    $this->protocol = "\\Workerman\\Protocols\\$scheme";
                    if (!class_exists($this->protocol)) {
                        throw new Exception("class \\Protocols\\$scheme not exist");
                    }
                }

                if (!isset(static::$_builtinTransports[$this->transport])) {
                    throw new \Exception('Bad worker->transport ' . var_export($this->transport, true));
                }
            } else {
                $this->transport = $scheme;
            }

            $local_socket = static::$_builtinTransports[$this->transport] . ":" . $address;

            // Flag.
            $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
            $errno = 0;
            $errmsg = '';
            // SO_REUSEPORT.
            if ($this->reusePort) {
                stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
            }

            // Create an Internet or Unix domain server socket.
            $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context);
            if (!$this->_mainSocket) {
                throw new Exception($errmsg);
            }

            if ($this->transport === 'ssl') {
                stream_socket_enable_crypto($this->_mainSocket, false);
            } elseif ($this->transport === 'unix') {
                $socketFile = substr($address, 2);
                if ($this->user) {
                    chown($socketFile, $this->user);
                }
                if ($this->group) {
                    chgrp($socketFile, $this->group);
                }
            }

            // Try to open keepalive for tcp and disable Nagle algorithm.
            if (function_exists('socket_import_stream') && static::$_builtinTransports[$this->transport] === 'tcp') {
                set_error_handler(function(){});
                $socket = socket_import_stream($this->_mainSocket);
                socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
                socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
                restore_error_handler();
            }

            // Non blocking.
            stream_set_blocking($this->_mainSocket, 0);
        }

        $this->resumeAccept();
    }
1308571
public function open()
    {
        if (self::$monitorQueries) {
            self::$strQueries .= "Before @mysqli_connect\n";
            global $time;
            $curTime          = microtime(true) - $time;
            self::$strQueries .= sprintf('%f', $curTime) . "\n";
        }

        $this->connect();
    }
600040
public function connect(): void
    {
        // no need to get excited
        if ($this->isConnected()) {
            return;
        }

        // export credentials & others
        [$host, $name, $username, $password] = [
            $this->config['host'], $this->config['name'],
            $this->config['username'], $this->config['password'],
        ];
        $port = (int) $this->config['port'];

        // prepare connection string
        $connectionString = sprintf("host=%s dbname=%s", $host, $name);
        if ($port)     $connectionString .= " port={$port}";
        if ($username) $connectionString .= " user={$username}";
        if ($password) $connectionString .= " password='". addcslashes($password, "'\\") ."'";
        $options = $this->config['options'] ?? [];
        if (null !== ($opt = Util::arrayPick($options, 'connect_timeout'))) {
            $connectionString .= " connect_timeout={$opt}";
        }
        if ($opt = Util::arrayPick($options, 'sslmode')) {
            $connectionString .= " sslmode={$opt}";
        }
        if ($opt = Util::arrayPick($options, 'service')) {
            $connectionString .= " service={$opt}";
        }
        if ($opt = $this->config['timezone']) $connectionStringOptions[] = "--timezone=\'{$opt}\'";
        if ($opt = $this->config['charset'])  $connectionStringOptions[] = "--client_encoding=\'{$opt}\'";
        if (isset($connectionStringOptions)) {
            $connectionString .= " options='". join(' ', $connectionStringOptions) ."'";
        }

        // start connection profile
        $this->profiler && $this->profiler->start('connection');

        $resource =@ pg_connect($connectionString);
        $resourceStatus = pg_connection_status($resource);
        if ($resourceStatus === false || $resourceStatus === PGSQL_CONNECTION_BAD) {
            $resource =@ pg_connect($connectionString, PGSQL_CONNECT_FORCE_NEW); // re-try
            $resourceStatus = pg_connection_status($resource);
        }

        if (!$resource || $resourceStatus !== PGSQL_CONNECTION_OK) {
            $error = $this->parseConnectionError();
            throw new ConnectionException($error['message'], $error['code'], $error['sql_state']);
        }

        // finish connection profile
        $this->profiler && $this->profiler->end('connection');

        // log with info level
        $this->logger && $this->logger->log(Logger::INFO, sprintf('New connection via %s addr.', Util::getIp()));

        // assign resource
        $this->resource = new Resource($resource);

        // fill mapper map for once
        if ($this->mapper) {
            $map = $cache = null;
            if ($this->config['map_result_cache']) {
                $cache = new Cache();
                $cache->read('mapper.map', $map, true, $this->config['map_result_cache_ttl']);
            }

            if ($map == null) {
                try {
                    $result = $this->query("SELECT table_name, column_name, data_type, is_nullable, character_maximum_length FROM information_schema.columns WHERE table_schema = 'public'", null, -1, 1);
                    if ($result->count()) {
                        $map = [];
                        foreach ($result->items() as $item) {
                            $length = null;
                            if ($item->data_type == 'bit') { // for only bools
                                $length = (int) $item->character_maximum_length;
                            } elseif (substr($item->data_type, 0, 4) == 'char') { // for extra (char) crop
                                $length = (int) $item->character_maximum_length;
                            }

                            $map[$item->table_name][$item->column_name] = [
                                /* type */ Mapper::normalizeType($item->data_type),
                                /* length */ $length,
                                /* nullable */ ($item->is_nullable == 'YES')
                            ];
                        }

                        $cache && $cache->write('mapper.map', $map);
                    }
                    $result->reset();
                } catch (QueryException $e) {
                    throw new ConnectionException('Could not retrieve schema info for mapper!', null,
                        SqlState::OPPA_CONNECTION_ERROR, $e);
                }
            }

            // set map
            $this->mapper->setMap($map);
        }
    }
998510
def connect(*args, **kwargs):
    """"""
    global __CONNECTION
    if __CONNECTION is None:
        __CONNECTION = Connection(*args, **kwargs)

    return __CONNECTION
22405
public function connect()
    {
        if ($this->connection) {
            $this->disconnect();
        }

        $hasProtocol = strpos($this->_config['host'], '://') !== false;
        if ($hasProtocol) {
            list($this->_config['protocol'], $this->_config['host']) = explode('://', $this->_config['host']);
        }
        $scheme = null;
        if (!empty($this->_config['protocol'])) {
            $scheme = $this->_config['protocol'] . '://';
        }

        $this->_setSslContext($this->_config['host']);
        if (!empty($this->_config['context'])) {
            $context = stream_context_create($this->_config['context']);
        } else {
            $context = stream_context_create();
        }

        $connectAs = STREAM_CLIENT_CONNECT;
        if ($this->_config['persistent']) {
            $connectAs |= STREAM_CLIENT_PERSISTENT;
        }

        set_error_handler([$this, '_connectionErrorHandler']);
        $this->connection = stream_socket_client(
            $scheme . $this->_config['host'] . ':' . $this->_config['port'],
            $errNum,
            $errStr,
            $this->_config['timeout'],
            $connectAs,
            $context
        );
        restore_error_handler();

        if (!empty($errNum) || !empty($errStr)) {
            $this->setLastError($errNum, $errStr);
            throw new SocketException($errStr, $errNum);
        }

        if (!$this->connection && $this->_connectionErrors) {
            $message = implode("\n", $this->_connectionErrors);
            throw new SocketException($message, E_WARNING);
        }

        $this->connected = is_resource($this->connection);
        if ($this->connected) {
            stream_set_timeout($this->connection, $this->_config['timeout']);
        }

        return $this->connected;
    }
890812
public function connect(): void
    {
        // no need to get excited
        if ($this->isConnected()) {
            return;
        }

        // export credentials & others
        [$host, $name, $username, $password] = [
            $this->config['host'], $this->config['name'],
            $this->config['username'], $this->config['password'],
        ];
        $port = (int) $this->config['port'];
        $socket = (string) $this->config['socket'];

        // call big boss
        $resource = mysqli_init();

        // supported constants: http://php.net/mysqli.options
        if (isset($this->config['options'])) {
            foreach ($this->config['options'] as $option => $value) {
                if (!$resource->options($option, $value)) {
                    throw new ConnectionException("Setting '{$option}' option failed!");
                }
            }
        }

        // start connection profile
        $this->profiler && $this->profiler->start('connection');

        $resourceStatus =@ $resource->real_connect($host, $username, $password, $name, $port, $socket);
        if (!$resourceStatus) {
            $error = $this->parseConnectionError();
            throw new ConnectionException($error['message'], $error['code'], $error['sql_state']);
        }

        // finish connection profile
        $this->profiler && $this->profiler->end('connection');

        // log with info level
        $this->logger && $this->logger->log(Logger::INFO, sprintf('New connection via %s addr.', Util::getIp()));

        // set charset for connection
        if (isset($this->config['charset'])) {
            $run = $resource->set_charset($this->config['charset']);
            if (!$run) {
                throw new ConnectionException(sprintf('Unable to connect to MySQL server at "%s", '.
                    'invalid or not-supported character set "%s" given!', $this->config['host'], $this->config['charset']),
                        $resource->errno, SqlState::OPPA_CHARSET_ERROR);
            }
        }

        // set timezone for connection
        if (isset($this->config['timezone'])) {
            $run = $resource->query('SET time_zone = \''. $resource->real_escape_string($this->config['timezone']) .'\'');
            if (!$run) {
                throw new ConnectionException(sprintf('Unable to connect to MySQL server at "%s", '.
                    'invalid or not-supported timezone "%s" given.', $this->config['host'], $this->config['timezone']),
                        $resource->errno, SqlState::OPPA_TIMEZONE_ERROR);
            }
        }

        // assign resource
        $this->resource = new Resource($resource);

        // fill mapper map for once
        if ($this->mapper) {
            $map = $cache = null;
            if ($this->config['map_result_cache']) {
                $cache = new Cache();
                $cache->read('mapper.map', $map, true, $this->config['map_result_cache_ttl']);
            }

            if ($map == null) {
                try {
                    $result = $this->query("SELECT table_name, column_name, data_type, is_nullable, numeric_precision, character_maximum_length FROM information_schema.columns WHERE table_schema = '{$name}'", null, -1, 2);
                    if ($result->count()) {
                        $map = [];
                        foreach ($result->items() as $item) {
                            $item = (object) array_change_key_case($item); // normalize key cases

                            $length = null;
                            if ($item->data_type == 'bit') { // for only bools
                                $length = (int) $item->numeric_precision;
                            } elseif (substr($item->data_type, -4) == 'char') { // for extra (char) crop
                                $length = (int) $item->character_maximum_length;
                            }

                            $map[$item->table_name][$item->column_name] = [
                                /* type */ Mapper::normalizeType($item->data_type, $length),
                                /* length */ $length,
                                /* nullable */ ($item->is_nullable == 'YES'),
                            ];
                        }

                        $cache && $cache->write('mapper.map', $map);
                    }
                    $result->reset();
                } catch (QueryException $e) {
                    throw new QueryException('Could not retrieve schema info for mapper!', null,
                        SqlState::OPPA_CONNECTION_ERROR, $e);
                }
            }

            // set map
            $this->mapper->setMap($map);
        }
    }
849479
protected function _connect()
    {
        if (!is_null($this->_connection)) {
            return;
        }

        try {
            $this->_connection = new Horde_Imap_Client_Socket_Connection_Pop3(
                $this->getParam('hostspec'),
                $this->getParam('port'),
                $this->getParam('timeout'),
                $this->getParam('secure'),
                $this->getParam('context'),
                array(
                    'debug' => $this->_debug
                )
            );
        } catch (Horde\Socket\Client\Exception $e) {
            $e2 = new Horde_Imap_Client_Exception(
                Horde_Imap_Client_Translation::r("Error connecting to mail server."),
                Horde_Imap_Client_Exception::SERVER_CONNECT
            );
            $e2->details = $e->details;
            throw $e2;
        }

        $line = $this->_getResponse();

        // Check for string matching APOP timestamp
        if (preg_match('/<.+@.+>/U', $line['resp'], $matches)) {
            $this->_temp['pop3timestamp'] = $matches[0];
        }
    }