Establish a transient connection with the AMQP broker.

This method will initiate a connection with the AMQP broker.

@throws AMQPConnectionException
@return boolean TRUE on success or throw an exception on failure.
199780
public function connect() {
        $readWriteTimeout = max($this->read_timeout, $this->write_timeout); //?
        try {
            $this->connection = new AMQPStreamConnection(
                $this->host,
                $this->port,
                $this->login,
                $this->password,
                $this->vhost,
                false,                      //insist
                'AMQPLAIN',                 //login method
                null,                       //login response
                'en_US',                    //locale
                $this->connect_timeout,     // connect_timeout
                $readWriteTimeout,          // read_write_timeout
                null,                       // context
                $this->keepalive,           // keepalive
                $this->heartbeat            // heartbeat configuration
            );

            //Several exception types might be thrown
        } catch (Exception $e){
            throw new AMQPConnectionException($e->getMessage(), $e->getCode(), $e->getPrevious());
        }
    }
1100206
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.
         */

        $connect_retry_count = 0;
        $max_connect_retry_count = 10;
        do {
            $r = $this->socket->connect();
            if ($r) {
                break;
            }

            if (++$connect_retry_count > $max_connect_retry_count) {
                throw new Exception\ConnectError('Failed to connect to ' . $this->socket->getAddress());
            }
        } while (true);

        Debug::Log(Debug::INFO, 'connect(): Connection established.');

        $this->socket->set_blocking();

        /**
         * @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);
        }
        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);

        /**
         * @var Message\CONNACK $connackobj
         */
        $connackobj = null;

        $connackobj = $this->message_read();

        Debug::Log(Debug::INFO, 'connect(): connected=' . ($connackobj->getMessageType() == Message::CONNACK ? 1 : 0));

        # save current time for ping
        $this->connected_time = time();

        # Call connect
        $this->call_handler('connack', array($this, $connackobj));

        return $connackobj;
    }
373785
public function usePersistentConnection()
    {
        if (isset($this->outgoing_headers['Accept-Encoding'])) {
            return false;
        }
        $this->protocol_version = '1.1';
        $this->persistentConnection = true;
        $this->setHeader('Connection', 'Keep-Alive');
        return 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;
    }
917016
public function connect()
    {
        // check for timed out servers and remove them from the connection pool
        foreach ($this->connections as $address => $conn) {
            if ($conn->isTimedOut()) {
                $conn->close();
                unset($this->connections[$address]);
            }
        }

        // attempt to connect/re-connect to any server not actively connected to
        foreach ($this->addresses as $address) {
            if (!isset($this->connections[$address])) {
                try {
                    $this->connections[$address] = new Connection(
                        $address,
                        new $this->streamClass,
                        $this->getTimeout()
                    );

                    // issue certain commands on (re)connection
                    foreach ($this->watching as $tube) {
                        $this->connections[$address]->watchTube($tube);
                    }

                    if ($this->using !== false) {
                        $this->connections[$address]->useTube($this->using);
                    }

                    foreach ($this->ignoring as $tube) {
                        $this->connections[$address]->ignoreTube($tube);
                    }

                // silently fail if a server is offline
                } catch (Exception $e) {
                    unset($this->connections[$address]);
                }
            }
        }

        // no connections!
        if (count($this->connections) === 0) {
            throw new Exception('Could not establish a connection to any beanstalkd server in the pool.');
        }
    }
408360
private function setup()
    {
        $this->host = 'ws.audioscrobbler.com';
        $this->port = 80;
        $this->connected = 0;

        $this->socket = new Socket($this->host, $this->port);
        if (!$this->socket->error_number && !$this->socket->error_string) {
            $this->connected = 1;
            return true;
        } else {
            throw new ConnectionException($this->socket->error_string);
        }
    }
231199
protected function connect()
    {
        $host = "{$this->socketProtocol}://{$this->hostname}";
        if ($this->socketPort) {
            $host .= ":{$this->socketPort}";
        }
        $socketStream = @stream_socket_client($host, $errorNumber, $errorMessage, $this->socketOptions['connectionTimeout']);
        if (!is_resource($socketStream)) {
            throw new \Exception("{$errorNumber}: Error connecting to socket: [{$errorMessage}]");
        }
        stream_set_timeout($socketStream, $this->socketOptions['streamTimeout']);
        stream_set_blocking($socketStream, true);
        $this->socketResource = $socketStream;
        return $this;
    }
207251
final public function connect()
    {
        /* If an established connection is available, then there's
         * no need to connect and select the database.
         *
         * Depending on the database driver, conn_id can be either
         * boolean TRUE, a resource or an object.
         */
        if ($this->handle) {
            return;
        }

        //--------------------------------------------------------------------

        $this->connectTimeStart = microtime(true);

        // Connect to the database and set the connection ID
        $this->platformConnectHandler($this->config);

        // No connection resource? Check if there is a failover else throw an error
        if ( ! $this->handle) {
            // Check if there is a failover set
            if ( ! empty($this->config[ 'failover' ]) && is_array($this->config[ 'failover' ])) {
                // Go over all the failovers
                foreach ($this->config[ 'failover' ] as $failover) {

                    // Try to connect
                    $this->platformConnectHandler($failover = new Config($failover));

                    // If a connection is made break the foreach loop
                    if ($this->handle) {
                        $this->config = $failover;
                        break;
                    }
                }
            }

            // We still don't have a connection?
            if ( ! $this->handle) {
                throw new RuntimeException('DB_E_UNABLE_TO_CONNECT', 0, [$this->platform]);
            }
        }

        $this->connectTimeDuration = microtime(true) - $this->connectTimeStart;
    }
295260
public function createConnection(QueueConnectionTransfer $queueConnectionConfig)
    {
        return new Connection(
            $this->createAmqpStreamConnection($queueConnectionConfig),
            $this->createQueueEstablishmentHelper(),
            $queueConnectionConfig
        );
    }
1189741
public function connect()
    {
        if ($this->_connection) {
            return true;
        }
        $config = $this->_config;
        $config['flags'] += [
            PDO::ATTR_PERSISTENT => $config['persistent'],
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ];

        $databaseExists = file_exists($config['database']);

        $dsn = "sqlite:{$config['database']}";
        $this->_connect($dsn, $config);

        if (!$databaseExists && $config['database'] != ':memory:') {
            //@codingStandardsIgnoreStart
            @chmod($config['database'], $config['mask']);
            //@codingStandardsIgnoreEnd
        }

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

        return true;
    }
777026
public function connect(): bool
    {
        if($this->connected)
        {
            return true;
        }
        $this->socket = stream_socket_client('unix://' . $this->socketFile, $errno, $errstr);
        if(false === $this->socket)
        {
            $this->connected = false;
            return false;
        }
        $this->connected = true;
        return true;
    }
981035
public function connect()
    {
        if ($this->isConnected) {
            return false;
        }

        $driverOptions = $this->params['driverOptions'] ?? [];
        $user          = $this->params['user'] ?? null;
        $password      = $this->params['password'] ?? null;

        $this->_conn       = $this->_driver->connect($this->params, $user, $password, $driverOptions);
        $this->isConnected = true;

        if ($this->autoCommit === false) {
            $this->beginTransaction();
        }

        if ($this->_eventManager->hasListeners(Events::postConnect)) {
            $eventArgs = new Event\ConnectionEventArgs($this);
            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
        }

        return true;
    }
1235937
public function declareQueue() {

        $durable = boolval($this->flags & AMQP_DURABLE);
        $passive = boolval($this->flags & AMQP_PASSIVE);
        $exclusive = boolval($this->flags & AMQP_EXCLUSIVE);
        $auto_delete = boolval($this->flags & AMQP_AUTODELETE);

        try {
            list($this->name, $num_messages) = $this->channel->_getChannel()->queue_declare($this->name, $passive, $durable, $exclusive, $auto_delete, $nowait = false, $this->arguments);
        } catch (AMQPRuntimeException $e) {
            throw new AMQPConnectionException($e->getMessage(), $e->getCode(), $e->getPrevious());
        } catch (Exception $e) {
            return 0;
        }

        return $num_messages;
    }
1333724
AmqpClient startOkConnection(AmqpArguments clientProperties, String mechanism, String response, String locale) {
        this.startOkConnection(clientProperties, mechanism, response, locale, null, null);
        return this;
    }
301922
public function createConnection()
    {
        $uri                = $this->pool->getConnectionAddress();
        $options            = $this->parseUri($uri);
        $options['timeout'] = $this->pool->getTimeout();

        /** @var DbPoolProperties $config */
        $config     = $this->pool->getPoolConfig();
        $strictType = $config->isStrictType();
        $fetchMode  = $config->isFetchMode();

        $serverConfig = [
            'host'        => $options['host'],
            'port'        => $options['port'],
            'user'        => $options['user'],
            'password'    => $options['password'],
            'database'    => $options['database'],
            'timeout'     => $options['timeout'],
            'charset'     => $options['charset'],
            'strict_type' => $strictType,
        ];

        if (version_compare(swoole_version(), '4.0', '>=')) {
            $serverConfig['fetch_mode'] = $fetchMode;
        }

        // init
        $mysql = new MySQL();
        $mysql->connect($serverConfig);

        // error
        if ($mysql->connected === false) {
            throw new MysqlException('Database connection error，error=' . $mysql->connect_error);
        }

        $this->originDb   = $options['database'];
        $this->connection = $mysql;
    }
1081410
private function getConnectionByChannel(): ConnectionInterface
    {
        if($this->channel === null){
            $this->channel = new Channel($this->poolConfig->getMaxActive());
        }

        $stats = $this->channel->stats();
        if ($stats['queue_num'] > 0) {
            return $this->getEffectiveConnection($stats['queue_num']);
        }

        $maxActive = $this->poolConfig->getMaxActive();
        if ($this->currentCount < $maxActive) {
            $connection = $this->createConnection();
            $this->currentCount++;

            return $connection;
        }

        $maxWait = $this->poolConfig->getMaxWait();
        if ($maxWait != 0 && $stats['consumer_num'] >= $maxWait) {
            throw new ConnectionException(sprintf('Connection pool waiting queue is full, maxActive=%d,maxWait=%d,currentCount=%d', $maxActive, $maxWait, $this->currentCount));
        }

        $maxWaitTime = $this->poolConfig->getMaxWaitTime();
        if ($maxWaitTime == 0) {
            return $this->channel->pop();
        }

        // When swoole version is larger than 4.0.3, Channel->select is removed.
        if (version_compare(swoole_version(), '4.0.3', '>=')) {
            $result = $this->channel->pop($maxWaitTime);
            if ($result === false) {
                throw new ConnectionException('Connection pool waiting queue timeout, timeout=' . $maxWaitTime);
            }
            return $result;
        }

        $writes = [];
        $reads  = [$this->channel];
        $result = $this->channel->select($reads, $writes, $maxWaitTime);

        if ($result === false || empty($reads)) {
            throw new ConnectionException('Connection pool waiting queue timeout, timeout='.$maxWaitTime);
        }

        $readChannel = $reads[0];

        return $readChannel->pop();
    }
659558
public function connect()
    {
        if ($this->state !== ClientStateEnum::NOT_CONNECTED) {
            throw new ClientException("Client already connected/connecting.");
        }

        try {
            $this->state = ClientStateEnum::CONNECTING;

            $this->writer->appendProtocolHeader($this->writeBuffer);
            $this->flushWriteBuffer();
            $this->authResponse($this->awaitConnectionStart());
            $tune = $this->awaitConnectionTune();
            $this->connectionTuneOk($tune->channelMax, $tune->frameMax, $this->options["heartbeat"]); // FIXME: options heartbeat
            $this->frameMax = $tune->frameMax;
            if ($tune->channelMax > 0) {
                $this->channelMax = $tune->channelMax;
            }
            $this->connectionOpen($this->options["vhost"]);

            $this->state = ClientStateEnum::CONNECTED;

            return $this;

        } catch (\Exception $e) {
            $this->state = ClientStateEnum::ERROR;
            throw $e;
        }
    }