Connect to server

@return boolean
@throws StompException
@see setVhostname
176014
public function connect()
    {
        if ($this->isConnected()) {
            return true;
        }
        $this->isConnecting = true;
        $this->connection->connect();
        $this->connection->getParser()->legacyMode(true);
        $this->protocol = new Protocol($this->clientId);

        $this->host = $this->host ?: $this->connection->getHost();

        $connectFrame = $this->protocol->getConnectFrame(
            $this->login,
            $this->passcode,
            $this->versions,
            $this->host,
            $this->heartbeat
        );
        $this->sendFrame($connectFrame, false);

        if ($frame = $this->getConnectedFrame()) {
            $version = new Version($frame);

            if ($version->hasVersion(Version::VERSION_1_1)) {
                $this->connection->getParser()->legacyMode(false);
            }

            $this->sessionId = $frame['session'];
            $this->protocol = $version->getProtocol($this->clientId);
            $this->isConnecting = false;
            return true;
        }
        throw new ConnectionException('Connection not acknowledged');
    }
94386
public function connectToServers()
    {
        //Array for the list of server(s) to connect
        $addServers  = [];
        
        //Get all server already connected (persistent)
        $serversList = $this->obtainConnectedServerList();
        
        //Loop on server declared into config
        foreach ($this->config['servers'] as $server) {
            $this->completeServerInfos($server);
            
            $host   = $server['host'];
            $port   = $server['port'];
            $weight = $server['weight'];
            
            //not check if port = (int) 0; Doc said to define to 0 for socket.
            if (empty($host) || $port === null) {
                continue;
            }
            
            //search if the reading server is not already connected
            if (in_array($host.':'.$port, $serversList)) {
                continue;
            }
            
            \BFW\Application::getInstance()
                ->getMonolog()
                ->getLogger()
                ->debug(
                    'Try to connect to memcached server.',
                    [
                        'host' => $host,
                        'port' => $port
                    ]
                );
            
            //If not, add the server at the list to connect
            $addServers[] = [$host, $port, $weight];
        }

        //Connect to server(s)
        $this->addServers($addServers);
        
        //Check if connect is successfull
        $this->testConnect();
    }
830110
public function connect()
    {
        if ($this->ssl !== false) {
            $function = 'ftp_ssl_connect';
        } else {
            $function = 'ftp_connect';
        }

        $result = call_user_func_array($function, array($this->host, $this->port, $this->timeout));

        if (!$result) {
            return false;
        } else {
            $this->stream = $result;
            return true;
        }
    }
1101873
protected function _connect(): bool {

		if ($this->_oPDO) {
			return FALSE;
		}

		$sName = $this->_sName;
		$sDSN = $this->_aConfig['dsn'];
		$this->_sPrevPrepareQuery = NULL;
		$this->_oPrevPrepare = NULL;

		try {

			$this->_oPDO = new \PDO(
				$this->_aConfig['dsn'],
				$this->_aConfig['user'],
				$this->_aConfig['password'],
				$this->_aConfig['option']
			);

		} catch (\Throwable $e) {

			$sError = 'MySQL Connect fail, Database "' . $sName . '"' . "\n"
				. $e->getMessage() . "\n"
				. 'DSN ' . $sDSN;
			throw new TangoException($sError, 2);
		}
		return TRUE;
	}
794932
public function connect()
	{
		//check if there is a valid service instance
		if ( ! $this->validService()) 
		{

			//put this in try...catch block for better error handling
			try{
				
				//make a connection attempt
				$this->service = new \MySQLi($this->host,$this->username,$this->password,$this->database,$this->port);

				//check is the connection attempt returned an error
				if ($this->service->connect_error) 
				{
					//throw exception
					throw new MySQLException("Unable to connect to Database service with the provided settings");

				}

				//set the connection variable to true
				$this->connected = true;

			}

			//diplay error message
			catch(MySQLException $MySQLExceptionObject){

				//display error message
				$MySQLExceptionObject->errorShow();

			}
			
		}

		//return this connection instance
		return $this;

	}
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;
	}
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;
    }
472547
protected function connect()
    {
        // We want to only create the driver once.
        if (isset($this->driver)) {
            return $this;
        }

        if (($this->defaultHost === 'localhost' || filter_var($this->defaultHost, FILTER_VALIDATE_IP))) {
            $this->driver->connect('tcp://' . $this->defaultHost . ':' . $this->defaultPort, $this->defaultPort);
        } else {
            $this->driver->connect($this->defaultHost, null);
        }

        return $this;
    }
307554
public function connect()
    {
        $config = $this->getConfig();
        if(isset($config['database']['database'])) {
            $conn = $this->instanceConnector();
            $host = $config['database']['hostname'];
            $user = $config['database']['username'];
            $pass = $config['database']['password'];
            if ($conn->connect($host, $user, $pass)) {
                $this->connection = $conn;
                $this->createCache();
                return true;
            }
            $err = $conn->getLastError();
            throw new \Exception(sprintf('Can not establish connection to database! {host=%s, user=%s, database=%s} Error: %s',
                        $config['database']['hostname'], $config['database']['username'], $config['database']['database'], $err));
        }

        return false;

//        if (!$this->connection) {
//
//            if ($conn->connect()
//            ) {
//                if ($conn->select_database($config['database']['database'])) {
//                    $this->connection = $conn;
//                    self::$selected = true;
//                    $this->createCache();
////
////                    if (!defined("GL_INSTALL") || !GL_INSTALL) {
////                        $this->checkDatabaseStructure();
////                    }
//                    return true;
//                }
//                return false;
//            } else {
//                $err =$conn->getLastError();
//                throw new \Exception(sprintf('Can not establish connection to database! {host=%s, user=%s, database=%s} Error: %s',
//                    $config['database']['hostname'], $config['database']['username'], $config['database']['database'], $err));
//            }
//        }
//        return true;
    }
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;
    }
573786
public function connect() : bool
    {
        $connection_string = 'ibm:DRIVER={IBM DB2 ODBC DRIVER};HOSTNAME=' . $this->configuration['server'] . ';PORT=50000;DATABASE=' . $this->configuration['dbname'] . ';PROTOCOL=TCPIP';
        $this->logger->info('DB2 Connection String: ' . $connection_string);
        try {
            $this->logger->debug('Connecting to database engine.');
            //if (false === $this->configuration['username'] && false === $this->configuration['password']) {
            //    // This DBC uses the user's credentials
            //    $this->logger->info('Creating user-specific PDO connection');
            //    $pdo = User::i()->getSecurePDO($this, $connection_string);
            //} else {
            // This DBC uses standard credentials
            $this->logger->info('Creating PDO connection as defined in configuration.');
            $pdo = new PDO($connection_string, $this->configuration['username'], $this->configuration['password']);
            //}
            $this->logger->debug('Connected to database engine.');
            $this->dbconn = $pdo;
            $this->is_connected = true;
        } catch (\Exception $e) {
            $this->logger->error('DB2 Connection failed: ' . $connection_string);
            throw new DatabaseConnectionException('DB2 Connection to <strong>' . $this->configuration['server'] . '</strong> failed!<br>' . $e->getMessage());
        }
        return true;
    }
529101
public function connect()
    {
        $this->isBound = false;
        $this->connection = $this->driver->connect(
            $this->configuration['hostname'],
            $this->configuration['port'],
            $this->configuration['withSSL'],
            $this->configuration['withTLS']
        );

        foreach ($this->configuration['options'] as $key => $value) {
            $this->connection->setOption($key, $value);
        }
    }
777851
public function connect()
  {
    if($this->stream !== null) return;

    $host     = strval($this->config["host"]);
    $port     = strval($this->config["port"]);
    $timeout  = intval($this->config["timeout"]);
    $blocking = intval($this->config["blocking"]);

    if(empty($this->config["ssh"]))
    {
      $address = "tcp://" . (strstr($host, ":") !== FALSE ? "[" . $host . "]" : $host) . ":" . $port;
      $options = empty($this->config["tls"]) ? array() : array("ssl" => array("allow_self_signed" => TRUE, "verify_peer" => FALSE, "verify_peer_name" => FALSE));

      $this->stream = @stream_socket_client($address, $errno, $errstr, $this->config["timeout"], STREAM_CLIENT_CONNECT, stream_context_create($options));

      if($this->stream === FALSE)
      {
        throw new TeamSpeak3_Transport_Exception(TeamSpeak3_Helper_String::factory($errstr)->toUtf8()->toString(), $errno);
      }

      if(!empty($this->config["tls"]))
      {
        stream_socket_enable_crypto($this->stream, TRUE, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
      }
    }
    else
    {
      $this->session = @ssh2_connect($host, $port);

      if($this->session === FALSE)
      {
        throw new TeamSpeak3_Transport_Exception("failed to establish secure shell connection to server '" . $this->config["host"] . ":" . $this->config["port"] . "'");
      }

      if(!@ssh2_auth_password($this->session, $this->config["username"], $this->config["password"]))
      {
        throw new TeamSpeak3_Adapter_ServerQuery_Exception("invalid loginname or password", 0x208);
      }

      $this->stream = @ssh2_shell($this->session, "raw");

      if($this->stream === FALSE)
      {
        throw new TeamSpeak3_Transport_Exception("failed to open a secure shell on server '" . $this->config["host"] . ":" . $this->config["port"] . "'");
      }
    }

    @stream_set_timeout($this->stream, $timeout);
    @stream_set_blocking($this->stream, $blocking ? 1 : 0);
  }
777778
public function connect(): bool
    {
        if ($this->isConnected()) {
            return true;
        }

        $errno = null;
        $errstr = null;

        // Supress PHP error, we're handling it
        $this->socket = @stream_socket_client(
            $this->getUri(),
            $errno,
            $errstr,
            $this->options['timeout_connect'],
            STREAM_CLIENT_CONNECT,
            $this->getStreamContext()
        );

        if (!$this->socket) {
            throw new \Wrench\Exception\ConnectionException(sprintf(
                'Could not connect to socket: %s (%d)',
                $errstr,
                $errno
            ));
        }

        stream_set_timeout($this->socket, $this->options['timeout_socket']);

        return ($this->connected = true);
    }
613720
public function connect()
  {
    if($this->stream !== null) return;

    $host = strval($this->config["host"]);
    $port = strval($this->config["port"]);

    $address = "udp://" . (strstr($host, ":") !== FALSE ? "[" . $host . "]" : $host) . ":" . $port;
    $timeout = (int) $this->config["timeout"];

    $this->stream = @stream_socket_client($address, $errno, $errstr, $timeout);

    if($this->stream === FALSE)
    {
      throw new Exception(Str::factory($errstr)->toUtf8()->toString(), $errno);
    }

    @stream_set_timeout($this->stream, $timeout);
    @stream_set_blocking($this->stream, $this->config["blocking"] ? 1 : 0);
  }
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();
        });
    }
1301502
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
        ];
        if (empty($config['unix_socket'])) {
            $dsn = "pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']}";
        } else {
            $dsn = "pgsql:dbname={$config['database']}";
        }

        $this->_connect($dsn, $config);
        $this->_connection = $connection = $this->getConnection();
        if (!empty($config['encoding'])) {
            $this->setEncoding($config['encoding']);
        }

        if (!empty($config['schema'])) {
            $this->setSchema($config['schema']);
        }

        if (!empty($config['timezone'])) {
            $config['init'][] = sprintf('SET timezone = %s', $connection->quote($config['timezone']));
        }

        foreach ($config['init'] as $command) {
            $connection->exec($command);
        }

        return true;
    }