Connect (create a socket) to the WhatsApp network.

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

        /* Create a TCP/IP socket. */
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($socket !== false) {
            $result = socket_connect($socket, 'e'.rand(1, 16).'.whatsapp.net', Constants::PORT);
            if ($result === false) {
                $socket = false;
            }
        }

        if ($socket !== false) {
            socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, ['sec' => Constants::TIMEOUT_SEC, 'usec' => Constants::TIMEOUT_USEC]);
            socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, ['sec' => Constants::TIMEOUT_SEC, 'usec' => Constants::TIMEOUT_USEC]);

            $this->socket = $socket;
            $this->eventManager()->fire('onConnect',
                [
                    $this->phoneNumber,
                    $this->socket,
                ]
            );
            $this->logFile('info', 'Connected to WA server');

            return true;
        } else {
            $this->logFile('error', 'Failed to connect WA server');
            $this->eventManager()->fire('onConnectError',
                [
                    $this->phoneNumber,
                    $this->socket,
                ]
            );

            return false;
        }
    }
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);
  }
1239469
protected function connect(): void
    {
        $this->connection = @\stream_socket_client( // @ is escalated to exception
            ($this->secure === 'ssl' ? 'ssl://' : '') . $this->host . ':' . $this->port,
            $errno, $error, $this->timeout, STREAM_CLIENT_CONNECT, $this->context
        );
        if (!$this->connection) {
            throw new SmtpException($error ?: error_get_last()['message'], $errno);
        }
        \stream_set_timeout($this->connection, $this->timeout, 0);
        $this->read(); // greeting

        $this->write("EHLO {$this->clientHost}");
        $ehloResponse = $this->read();
        if ((int) $ehloResponse !== 250) {
            $this->write("HELO {$this->clientHost}", 250);
        }

        if ($this->secure === 'tls') {
            $this->write('STARTTLS', 220);
            if (!\stream_socket_enable_crypto($this->connection, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                throw new SmtpException('Unable to connect via TLS.');
            }
            $this->write("EHLO {$this->clientHost}", 250);
        }

        $password = $this->getPassword();
        if ($this->username !== '' && $password !== '') {
            $authMechanisms = [];
            if (\preg_match('~^250[ -]AUTH (.*)$~im', $ehloResponse, $matches)) {
                $authMechanisms = \explode(' ', \trim($matches[1]));
            }

            if (\in_array('PLAIN', $authMechanisms, true)) {
                $credentials = $this->username . "\0" . $this->username . "\0" . $password;
                $this->write('AUTH PLAIN ' . \base64_encode($credentials), 235, 'PLAIN credentials');
            } else {
                $this->write('AUTH LOGIN', 334);
                $this->write(\base64_encode($this->username), 334, 'username');
                $this->write(\base64_encode($password), 235, 'password');
            }
        }
    }
904789
public function connect()
  {
    try {
      $this->cnx = new \PDO($this->dns, $this->user, $this->pass);
      $this->cnx->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
      return true;
    } catch (\Exception $e) {
      return false;
    }
  }
1351131
public function connect(): bool
    {
        if ($this->isConnected()) {
            return false;
        }

        try {
            $this->socket->connect();
        } catch (\Exception $ex) {
            return false;
        }

        $key = $this->protocol->generateKey();
        $handshake = $this->protocol->getRequestHandshake(
            $this->uri,
            $key,
            $this->origin,
            $this->headers
        );

        $this->socket->send($handshake);
        $response = $this->socket->receive(self::MAX_HANDSHAKE_RESPONSE);
        return ($this->connected =
            $this->protocol->validateResponseHandshake($response, $key));
    }
1358985
private function connect() {
        $connection = fsockopen('tcp://'.$this->options['host'],
                                         $this->options['port'],
                                         $errorCode,
                                         $errorMsg,
                                         $this->options['timeout']);
        // TODO: connect() might hang without producing an error if the connection fails
        if (!$connection) throw new RuntimeException('Could not open socket: '.$errorMsg.' (error '.$errorCode.')');

        $data = stream_get_meta_data($connection);
        if ($data['timed_out']) throw new InfrastructureException('Timeout on socket connection');

        socket_set_timeout($connection, $this->options['timeout']);
        $this->connection = $connection;

        // init connection
        $this->readResponse();                          // read greeting
        $this->writeData('EHLO '.$this->hostName);      // extended "Hello" first
        $response = $this->readResponse();

        $this->parseResponse($response);
        if ($this->responseStatus != 250) {
            $this->writeData('HELO '.$this->hostName);  // regular "Hello" if the extended one fails
            $response = $this->readResponse();

            $this->parseResponse($response);
            if ($this->responseStatus != 250)
                throw new RuntimeException('HELO command not accepted: '.$this->responseStatus.' '.$this->response);
        }
    }
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;
    }
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;
    }
773938
public function connect()
    {
        if ($this->EnableAPCu && extension_loaded('apcu') && ini_get('apc.enabled')) {
            $this->Using = 'APCu';
            return true;
        }
        if ($this->EnableMemcached && extension_loaded('memcached')) {
            $this->WorkingData = new \Memcached();
            if ($this->WorkingData->addServer($this->MemcachedHost, $this->MemcachedPort)) {
                $this->Using = 'Memcached';
                return true;
            }
            $this->WorkingData = null;
        }
        if ($this->EnableRedis && extension_loaded('redis')) {
            $this->WorkingData = new \Redis();
            if ($this->WorkingData->connect($this->RedisHost, $this->RedisPort, $this->RedisTimeout)) {
                $this->Using = 'Redis';
                return true;
            }
            $this->WorkingData = null;
        }
        if ($this->EnablePDO && extension_loaded('pdo')) {
            try {
                $PDO = new \PDO($this->PDOdsn, $this->PDOusername, $this->PDOpassword);
            } catch (\PDOException $Exception) {
                $this->Exceptions[] = $Exception->getMessage();
                return false;
            }
            if (is_object($PDO)) {
                $this->WorkingData = $PDO;
                $this->Using = 'PDO';
                return true;
            }
            unset($PDO);
        }
        if ($this->FFDefault) {
            if (is_file($this->FFDefault)) {
                if (is_readable($this->FFDefault) && is_writable($this->FFDefault)) {
                    $this->Using = 'FF';
                    if (!$Filesize = filesize($this->FFDefault)) {
                        $this->WorkingData = [];
                        return $this->Modified = true;
                    }
                    $Data = '';
                    $Handle = false;
                    $Start = time();
                    while (true) {
                        $Handle = fopen($this->FFDefault, 'rb');
                        if ($Handle !== false || (time() - $Start) > self::FLOCK_TIMEOUT) {
                            break;
                        }
                    }
                    if ($Handle === false) {
                        return false;
                    }
                    $Locked = false;
                    while (true) {
                        if ($Locked = flock($Handle, LOCK_EX | LOCK_NB) || (time() - $Start) > self::FLOCK_TIMEOUT) {
                            break;
                        }
                    }
                    if (!$Locked) {
                        fclose($Handle);
                        return false;
                    }
                    $Size = ($Filesize && self::BLOCKSIZE) ? ceil($Filesize / self::BLOCKSIZE) : 0;
                    $Step = 0;
                    while ($Step < $Size) {
                        $Data .= fread($Handle, self::BLOCKSIZE);
                        $Step++;
                    }
                    flock($Handle, LOCK_UN);
                    fclose($Handle);
                    $Data = $Data ? unserialize($Data) : [];
                    $this->WorkingData = is_array($Data) ? $Data : [];
                    return true;
                }
            } else {
                $Parent = dirname($this->FFDefault);
                if (is_dir($Parent) && is_readable($Parent) && is_writable($Parent)) {
                    $this->WorkingData = [];
                    $this->Using = 'FF';
                    return $this->Modified = true;
                }
            }
            return false;
        }
        return is_array($this->WorkingData);
    }
1352927
public function connect()
	{
		if($this->_ssl_mode === true)
		{
			if( ! function_exists('ftp_ssl_connect'))
			{
				throw new \RuntimeException('ftp_ssl_connect() function is missing.');
			}

			$this->_conn_id = @ftp_ssl_connect($this->_hostname, $this->_port, $this->_timeout);
		}

		else
		{
			$this->_conn_id = @ftp_connect($this->_hostname, $this->_port, $this->_timeout);
		}

		if ($this->_conn_id === false)
		{
			if ($this->_debug == true)
			{
				throw new \FtpConnectionException('Unable to establish a connection');
			}
			return false;
		}

		if ( ! $this->_login())
		{
			if ($this->_debug == true)
			{
				throw new \FtpConnectionException('Unable to login');
			}
		}

		// Set passive mode if needed
		if ($this->_passive == true)
		{
			ftp_pasv($this->_conn_id, true);
		}

		return $this;
	}
1346637
public function sendPing()
    {
        $msgId = $this->createIqId();
        $pingNode = new ProtocolNode('ping', null, null, null);
        $node = new ProtocolNode('iq',
            [
                'id'    => $msgId,
                'xmlns' => 'w:p',
                'type'  => 'get',
                'to'    => Constants::WHATSAPP_SERVER,
            ], [$pingNode], null);

        $this->sendNode($node);
    }
1125734
public function connect()
    {
        try {
            if (empty($this->connectioId)) {
                $this->addHeader();
                $connectionResult  = $this->getSoap()->Connect();
                $this->connectioId = $connectionResult->ConnectResult;
            }
            $result = true;
        } catch (\SoapFault $ex) {
            $result = false;
        }
        return $result;
    }
973536
public boolean connect(){
		try {
			sock = new Socket(host, port);
			in = new BufferedReader(new InputStreamReader(
					sock.getInputStream(), "UTF-8"));
			out = new BufferedWriter(new OutputStreamWriter(
					sock.getOutputStream(), "UTF-8"));
			return true;
		}
		catch (Exception e){
			System.out.println(e.getMessage());
			return false;
		}
	}
1299221
public function connect()
    {
        $this->log->debug("connect");

        $host = $this->ipv4_address_for_host($this->host, $this->port);
        if(!$host)
        {
          return FALSE;
        }

        // NOTE: This timeout doesn't apply to DNS, but does apply to the actual connecting
        $this->socket = @stream_socket_client("tcp://{$host}:{$this->port}", $errno, $errorMessage, self::CONNECT_TIMEOUT);
        $this->log->debug("connect after stream_socket_client, stream_socket_get_name: " . stream_socket_get_name($this->socket, TRUE));
        stream_set_timeout($this->socket, self::SEND_REPLY_TIMEOUT, 0);
        if(!$this->is_connected())
        {
          $this->log->error("Connection error $errno : $errorMessage");
          $this->disconnect(); // TODO: delay retry?
          return FALSE;
        }

        $hostname = gethostname();
        $pid = getmypid();
        $runtime = phpversion();
        $platform = preg_replace('/\s+/', '_', php_uname());
        $hello_and_auth_cmd =
          "hello version php/instrumental_agent/" . self::VERSION . " " .
          "hostname $hostname " .
          "pid $pid " .
          "runtime $runtime " .
          "platform $platform\n" .
          "authenticate $this->api_key\n";

        // $this->log->debug("Sleeping. Enable packet loss to test.");
        // sleep(10);
        // $this->log->debug("Resuming.");

        // NOTE: dropping packets didn't appear to affect sending
        $this->socket_send($hello_and_auth_cmd);

        $this->log->debug("connect fgets");
        // NOTE: dropping packets did affect fgets, and SEND_REPLY_TIMEOUT did apply
        $line = fgets($this->socket, 1024);
        $this->log->debug("connect $line");
        if($line != "ok\n")
        {
          $this->log->error("Sending hello failed.");
          $this->disconnect(); // TODO: delay retry?
          return FALSE;
        }

        $this->log->debug("connect fgets");
        $line = fgets($this->socket, 1024);
        $this->log->debug("connect $line");
        if($line != "ok\n")
        {
          $this->log->error("Authentication failed with key $this->api_key Please check your configuration." );
          $this->disconnect(); // TODO: delay retry?
          return FALSE;
        }
        return TRUE;
    }
99878
public function connect()
    {
        $nodes = $this->nodeUrls;

        while (count($nodes)) {
            // pick random server
            $idx = rand(0, count($nodes) - 1);

            try {
                $stream = new DefaultStream($nodes[$idx], $this->log);
                $stream->connect();

                return $stream;
            } catch (ConnectException $e) {
                $this->log->warning($e->getMessage());
            }

            // remove the selected server from the list
            array_splice($nodes, $idx, 1);
        }

        throw new ConnectException('unable to connect to any of ['.implode(',', $this->nodeUrls).']');
    }
621665
public function createSocket(): Socket
    {
        return new Socket(
                $this->hostname(),
                $this->port(),
                (($this->isHttps()) ? ('ssl://') : (null))
        );
    }
7894
public function connect()
    {
        if ($this->object) {
            return true;
        }

        $this->object = new \Redis;
        $connect = $this->persistent ? 'pconnect' : 'connect';
        $result = $this->object->$connect($this->host, $this->port, $this->timeout);

        if ($result && $this->auth) {
            $result = $this->object->auth($this->auth);
        }

        if ($result) {
            foreach ($this->options as $key => $value) {
                $this->object->setOption($key, $value);
            }
        }

        return $result;
    }