connect method

  1. @override
Future<bool> connect()
override

Connect to the server

Returns true if the connection is successful, false otherwise

  1. Setup the Transport for the connection
  2. Start listening for incoming data
  3. Start the ping timer
  4. Perform the handshake

If the handshake is successful then incoming messages are handled by messages stream

If the handshake fails then the client will attempt to reconnect

Implementation

@override
Future<bool> connect() async {
  if (_connectionStatusValue.isConnected) {
    return true;
  }

  if (_handshaking) {
    // already under connection
    return _handshakeCompleter!.future;
  }

  try {
    final connector = _WebSocketConnector(url);

    _transport = Transport.create(connector);

    _updateConnectionStatus(
      _connectionStatusValue.isDisconnected
          ? ConnectionStatus.connecting
          : ConnectionStatus.reconnecting,
    );

    _transport!.incoming.listen(
      _handleIncomingData,
      onError: (dynamic error, _) {
        _handleTransportError(error);
      },
    );

    final connected = await _performHandshake();
    if (connected) {
      _startPingTimer();
      _updateConnectionStatus(ConnectionStatus.connected);
      for (final plugin in plugins) {
        plugin.onConnected();
      }
    }

    return connected;
  } catch (e) {
    _updateConnectionStatus(ConnectionStatus.error);
    return false;
  }
}