Connects to the IRC server.

@return boolean True if the socket was created successfully
15154
private function connect()
    {
        $server = $this->config['server'];
        if (isset($this->config['ssl']) && $this->config['ssl'] == true) {
            $server = 'ssl://' . $server;
        }

        stream_set_blocking(STDIN, 0);
        $this->socket = fsockopen($server, $this->config['port']);

        return (bool) $this->socket;
    }
1123143
function _connect()
    {
        if ($this->bitmap & self::MASK_CONSTRUCTOR) {
            return false;
        }

        $this->bitmap |= self::MASK_CONSTRUCTOR;

        $this->curTimeout = $this->timeout;

        $this->last_packet = microtime(true);

        if (!is_resource($this->fsock)) {
            $start = microtime(true);
            // with stream_select a timeout of 0 means that no timeout takes place;
            // with fsockopen a timeout of 0 means that you instantly timeout
            // to resolve this incompatibility a timeout of 100,000 will be used for fsockopen if timeout is 0
            $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->curTimeout == 0 ? 100000 : $this->curTimeout);
            if (!$this->fsock) {
                $host = $this->host . ':' . $this->port;
                user_error(rtrim("Cannot connect to $host. Error $errno. $errstr"));
                return false;
            }
            $elapsed = microtime(true) - $start;

            $this->curTimeout-= $elapsed;

            if ($this->curTimeout <= 0) {
                $this->is_timeout = true;
                return false;
            }
        }

        $this->identifier = $this->_generate_identifier();

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

        /* According to the SSH2 specs,

          "The server MAY send other lines of data before sending the version
           string.  Each line SHOULD be terminated by a Carriage Return and Line
           Feed.  Such lines MUST NOT begin with "SSH-", and SHOULD be encoded
           in ISO-10646 UTF-8 [RFC3629] (language is not specified).  Clients
           MUST be able to process such lines." */
        $data = '';
        while (!feof($this->fsock) && !preg_match('#(.*)^(SSH-(\d\.\d+).*)#ms', $data, $matches)) {
            $line = '';
            while (true) {
                if ($this->curTimeout) {
                    if ($this->curTimeout < 0) {
                        $this->is_timeout = true;
                        return false;
                    }
                    $read = array($this->fsock);
                    $write = $except = null;
                    $start = microtime(true);
                    $sec = floor($this->curTimeout);
                    $usec = 1000000 * ($this->curTimeout - $sec);
                    // on windows this returns a "Warning: Invalid CRT parameters detected" error
                    // the !count() is done as a workaround for <https://bugs.php.net/42682>
                    if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) {
                        $this->is_timeout = true;
                        return false;
                    }
                    $elapsed = microtime(true) - $start;
                    $this->curTimeout-= $elapsed;
                }

                $temp = stream_get_line($this->fsock, 255, "\n");
                if (strlen($temp) == 255) {
                    continue;
                }

                $line.= "$temp\n";

                // quoting RFC4253, "Implementers who wish to maintain
                // compatibility with older, undocumented versions of this protocol may
                // want to process the identification string without expecting the
                // presence of the carriage return character for reasons described in
                // Section 5 of this document."

                //if (substr($line, -2) == "\r\n") {
                //    break;
                //}

                break;
            }

            $data.= $line;
        }

        if (feof($this->fsock)) {
            user_error('Connection closed by server');
            return false;
        }

        $extra = $matches[1];

        if (defined('NET_SSH2_LOGGING')) {
            $this->_append_log('<-', $matches[0]);
            $this->_append_log('->', $this->identifier . "\r\n");
        }

        $this->server_identifier = trim($temp, "\r\n");
        if (strlen($extra)) {
            $this->errors[] = utf8_decode($data);
        }

        if (version_compare($matches[3], '1.99', '<')) {
            user_error("Cannot connect to SSH $matches[3] servers");
            return false;
        }

        if (!$this->send_id_string_first) {
            fputs($this->fsock, $this->identifier . "\r\n");
        }

        if (!$this->send_kex_first) {
            $response = $this->_get_binary_packet();
            if ($response === false) {
                user_error('Connection closed by server');
                return false;
            }

            if (!strlen($response) || ord($response[0]) != NET_SSH2_MSG_KEXINIT) {
                user_error('Expected SSH_MSG_KEXINIT');
                return false;
            }

            if (!$this->_key_exchange($response)) {
                return false;
            }
        }

        if ($this->send_kex_first && !$this->_key_exchange()) {
            return false;
        }

        $this->bitmap|= self::MASK_CONNECTED;

        return true;
    }
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();
        });
    }
1174115
public function isConnected()
    {
        if ($this->connected === false) {
            return false;
        }

        // Check if the socket is still connected
        if ($this->socket->isConnected() === false) {
            $this->connected = false;

            return false;
        }

        return true;
    }
743986
public function connect()
    {
        $streamContext = stream_context_create(array(
            $this->getTransport() => $this->getContextOptions()
        ));

        $streamResource = stream_socket_client(
            $this->getAddress(),
            $errorCode,
            $errorMessage,
            $this->getSocketTimeout(),
            $this->getConnectionFlags(),
            $streamContext
        );

        if (!$streamResource) {
            throw new \RuntimeException(sprintf(
                'Unable to connect on socket. Error [%d]: %s',
                $errorCode,
                $errorMessage
            ));
        }

        stream_set_blocking($streamResource, $this->isBlockingMode());

        $this->setStreamResource($streamResource);

        return $this;
    }
1215158
public function connected()
    {
        if (is_resource($this->smtp_conn)) {
            $sock_status = stream_get_meta_data($this->smtp_conn);
            if ($sock_status['eof']) {
                // The socket is valid but we are not connected
                $this->edebug(
                    'SMTP NOTICE: EOF caught while checking if connected',
                    self::DEBUG_CLIENT
                );
                $this->close();

                return false;
            }

            return true; // everything looks good
        }

        return false;
    }
1017467
public function connect()
    {

          //if port is not set, try and determine based on transport
        if(!is_numeric($this->port)){
            if(substr($this->host, 0, 3) == 'ssl'){
                $this->port = 5223;
                $this->log("Connecting with SSL");

            } else {
                $this->port = 5222;
            }
        }

        parent::__construct($this->host.':'.$this->port, $this->timeout);

        $this->open();

        //begin stream
        $this->write("<stream:stream to='$this->host' xmlns='jabber:client'
xmlns:stream='http://etherx.jabber.org/streams' xml:lang='en' version='1.0'>");

        $this->read();
        $this->read();

        $this->connected = true;

    }
167002
public function connect()
    {
        try {
            // Instantiate an S3 client
            $this->setS3Client(new S3Client([
                        'version' => $this->supplier['version'],
                        'region' => $this->supplier['region'],
                        'http'    => $this->supplier['http']
                    ]
                )
            );
        } catch (\Exception $e) {
            return false;
        }

        return true;
    }
89410
public function connect(): bool
    {
        if ($this->isConnected()) {
            return true;
        }

        $this->socket = $this->createSocket();
        try {
            if (socket_connect($this->socket, $this->address, $this->port) === false) {
                throw new RelayException(socket_strerror(socket_last_error($this->socket)));
            }
        } catch (\Exception $e) {
            throw new RelayException("unable to establish connection {$this}", 0, $e);
        }

        return true;
    }
438251
public function connect()
    {
        $socket = $this->createSocket(
            $this->connection->getHostname(),
            $this->connection->getPort(),
            $this->throttle
        );

        $this->setSocket($socket);
    }
267248
protected function _connect()
    {
        if (!is_null($this->_connection)) {
            return;
        }

        try {
            $this->_connection = new Horde_Imap_Client_Socket_Connection_Socket(
                $this->getParam('hostspec'),
                $this->getParam('port'),
                $this->getParam('timeout'),
                $this->getParam('secure'),
                $this->getParam('context'),
                array(
                    'debug' => $this->_debug,
                    'debugliteral' => $this->getParam('debug_literal')
                )
            );
        } 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;
        }

        // If we already have capability information, don't re-set with
        // (possibly) limited information sent in the initial banner.
        if (isset($this->_init['capability'])) {
            $this->_temp['no_cap'] = true;
        }

        /* Get greeting information (untagged response). */
        try {
            $this->_getLine($this->_pipeline());
        } catch (Horde_Imap_Client_Exception_ServerResponse $e) {
            if ($e->status === Horde_Imap_Client_Interaction_Server::BYE) {
                /* Server is explicitly rejecting our connection (RFC 3501
                 * [7.1.5]). */
                $e->setMessage(Horde_Imap_Client_Translation::r("Server rejected connection."));
                $e->setCode(Horde_Imap_Client_Exception::SERVER_CONNECT);
            }
            throw $e;
        }

        // Check for IMAP4rev1 support
        if (!$this->_capability('IMAP4REV1')) {
            throw new Horde_Imap_Client_Exception(
                Horde_Imap_Client_Translation::r("The mail server does not support IMAP4rev1 (RFC 3501)."),
                Horde_Imap_Client_Exception::SERVER_CONNECT
            );
        }

        // Set language if NOT using imapproxy
        if (empty($this->_init['imapproxy'])) {
            if ($this->_capability('XIMAPPROXY')) {
                $this->_setInit('imapproxy', true);
            } else {
                $this->setLanguage();
            }
        }

        // If pre-authenticated, we need to do all login tasks now.
        if (!empty($this->_temp['preauth'])) {
            $this->login();
        }
    }
342643
protected function _connect() {
		$unixSocket = $this->config['unix_socket'];
		$persistent = $this->config['persistent'];
		$host = $this->config['host'];
		$port = $this->config['port'];
		$timeout = $this->config['timeout'];

		if ($unixSocket) {
			return $this->_connection->connect($unixSocket);
		} elseif ($persistent) {
			return $this->_connection->pconnect($host, $port, $timeout, $persistent);
		} else {
			return $this->_connection->connect($host, $port, $timeout);
		}
	}
476224
public function connect()
    {
        $logger = $this->getLogger();
        $monolog = $logger->driver();

        $monolog->pushHandler(new SocketHandler('tcp://127.0.0.1:8337'));

        try {
            $logger->info('Debug client connecting...');
        } catch (Exception $e) {
            $monolog->popHandler();

            return false;
        }

        return true;
    }
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();
        }
    }
321352
public function connect()
    {
        if ($this->_connection) {
            return true;
        }
        $config = $this->_config;

        if ($config['timezone'] === 'UTC') {
            $config['timezone'] = '+0:00';
        }

        if (!empty($config['timezone'])) {
            $config['init'][] = sprintf("SET time_zone = '%s'", $config['timezone']);
        }
        if (!empty($config['encoding'])) {
            $config['init'][] = sprintf('SET NAMES %s', $config['encoding']);
        }

        $config['flags'] += [
            PDO::ATTR_PERSISTENT => $config['persistent'],
            PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        ];

        if (!empty($config['ssl_key']) && !empty($config['ssl_cert'])) {
            $config['flags'][PDO::MYSQL_ATTR_SSL_KEY] = $config['ssl_key'];
            $config['flags'][PDO::MYSQL_ATTR_SSL_CERT] = $config['ssl_cert'];
        }
        if (!empty($config['ssl_ca'])) {
            $config['flags'][PDO::MYSQL_ATTR_SSL_CA] = $config['ssl_ca'];
        }

        if (empty($config['unix_socket'])) {
            $dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']};charset={$config['encoding']}";
        } else {
            $dsn = "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
        }

        $this->_connect($dsn, $config);

        if (!empty($config['init'])) {
            $connection = $this->getConnection();
            foreach ((array)$config['init'] as $command) {
                $connection->exec($command);
            }
        }

        return true;
    }
1324127
public static function connect() {
		if (self::$memcached === null) {
			$config = \Skeleton\Object\Config::$cache_handler_config;
			self::$memcached = new \Memcached();
			self::$memcached->setOption(\Memcached::OPT_SERIALIZER, \Memcached::SERIALIZER_IGBINARY);
			self::$memcached->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
			self::$memcached->setOption(\Memcached::OPT_NO_BLOCK, true);
			self::$memcached->setOption(\Memcached::OPT_TCP_NODELAY, true);
			self::$memcached->addServers([
				[$config['hostname'], $config['port']]
			]);
		}

		return self::$memcached;
	}
1139854
protected function _connect()
    {
        try {
            $this->_Redis = new Redis();
            if (!empty($this->_config['unix_socket'])) {
                $return = $this->_Redis->connect($this->_config['unix_socket']);
            } elseif (empty($this->_config['persistent'])) {
                $return = $this->_Redis->connect($this->_config['server'], $this->_config['port'], $this->_config['timeout']);
            } else {
                $persistentId = $this->_config['port'] . $this->_config['timeout'] . $this->_config['database'];
                $return = $this->_Redis->pconnect($this->_config['server'], $this->_config['port'], $this->_config['timeout'], $persistentId);
            }
        } catch (RedisException $e) {
            return false;
        }
        if ($return && $this->_config['password']) {
            $return = $this->_Redis->auth($this->_config['password']);
        }
        if ($return) {
            $return = $this->_Redis->select($this->_config['database']);
        }

        return $return;
    }