Connect to a WebSocket server.

@throws ConnectException thrown if failed to connect to the server via WebSocket protocol
964107
public void connect() throws ConnectException {
        try {
            connectToWebSocket();
            setWebSocketListener();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.warn("Interrupted while connecting via WebSocket protocol");
        }
    }
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));
    }
1255515
protected function connectWs()
    {
        $this->logger->info('starting connection to websocket', ['gateway' => $this->gateway]);

        $this->wsFactory->__invoke($this->gateway)->then(
            [$this, 'handleWsConnection'],
            [$this, 'handleWsError']
        );
    }
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;
    }
412051
public void connect() {
        try {
            ws.setPingInterval(pingInterval);
            ws.connect();
        } catch (WebSocketException e){
            e.printStackTrace();
            if(onErrorListener != null) {
                onErrorListener.onError(e);
            }
            if(tryReconnection) {
                if (timer == null) {
                    // this is to handle reconnection first time
                    if (lastPongAt == 0) {
                        lastPongAt = 1;
                    }
                    timer = new Timer();
                    timer.scheduleAtFixedRate(getTask(), 0, pongCheckInterval);
                }
            }
        }
    }
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');
    }
636690
protected function connectWs()
	{
		$wsUrl = sprintf('ws://%s/v1/clients/%s/ws', $this->serverUrl, $this->getId());

		$this->ws = new WebsocketClient($wsUrl, ['timeout' => 30]);
		$this->ws->setTimeout(30);
	}
1059329
public function connect()
    {
        try {
            $this->instance = DriverManager::getConnection($this->config, new Configuration());
            $this->createSchema();

            return true;
        } catch (DBALException $e) {
            throw new DriverConnectionException($e->getMessage());
        }
    }
281276
protected function connect()
    {
        $this->client = new Client(array(
            'host'   => $this->instance->getHost(),
            'port'   => $this->instance->getPort(),
        ));
    }
701629
@Override
    public void connect(String server, int port, Map<String, Object> connectionParams) {
        log.debug("connect server: {} port {} connectionParams {}", new Object[] { server, port, connectionParams });
        connect(server, port, connectionParams, null);
    }
56530
public function connect()
    {
        if (!$this->connection) {
            $errNum = $errStr = null;
            $this->connection = @fsockopen($this->host, $this->port, $errNum, $errStr, $this->options['timeout']);

            if (!$this->connection or $errNum > 0) {
                $message = sprintf(
                    'Could not connect to beanstalkd "%s:%d": %s (%d)',
                    $this->host,
                    $this->port,
                    $errStr,
                    $errNum
                );
                throw new Exception\SocketException($message);
            }

            // remove timeout on the stream, allows blocking reserve
            stream_set_timeout($this->connection, -1, 0);
        }

        return $this;
    }
1205889
public void connect() throws SQLException {
    if (!isClosed()) {
      close();
    }

    try {
      connect((currentHost != null) ? currentHost.host : null,
          (currentHost != null) ? currentHost.port : 3306);
    } catch (IOException ioException) {
      throw ExceptionMapper.connException(
          "Could not connect to " + currentHost + ". " + ioException.getMessage() + getTraces(),
          ioException);
    }
  }
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');
            }
        }
    }
968817
private function connectToTheNode()
    {
        $this->connection->connect(
            $this->credentials->getConnectionTimeout(),
            $this->credentials->getResponseTimeout()
        );
    }
518392
public void connect() throws DeploymentException, IOException, InterruptedException {
		final WebSocketContainer container = ContainerProvider.getWebSocketContainer();
		connectLatch = new CountDownLatch(1);
		this.userSession = container.connectToServer(this, endpointURI);
		connectLatch.await(15, TimeUnit.SECONDS);
	}
572970
protected function shouldBeConnected()
    {
        // If we lost the connection, first let's try and reconnect
        if (!$this->isConnected()) {
            try {
                $this->switchNodeIfNeeded();
            } catch (ConnectionException $e) {
                throw new ConnectionException('Not connected. ' . $e->getMessage(), 0, $e);
            }
        }
    }
1044222
public void connect() throws Exception {
        logger.debug("[connect] initializing new connection");

        if (timer != null) {
            timer.cancel();
        }

        if (isConnected()) {
            return;
        }

        synchronized (webSocketHandler.getNotifyConnectionObject()) {
            webSocketConnectionManager.start();

            try {
                webSocketHandler.getNotifyConnectionObject().wait(TimeUnit.SECONDS.toMillis(WEBSOCKET_TIMEOUT));
            }
            catch (InterruptedException e) {
                onConnectionClosed();
                logger.debug("[connect] not open");
                throw new Exception("websocket connection not open");
            }

            if (!isConnected()) {
                onConnectionClosed();
                logger.debug("[connect] timeout");
                throw new Exception("websocket connection timeout");
            }
        }
    }