connect method

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

Connect to the relay

Returns true if the connection is successful, false otherwise

  1. Setup the Transport for the connection
  2. Start listening for incoming data
  3. Join the room (hello/welcome exchange)
  4. Start the ping timer

If the join is successful then incoming messages are handled by messages stream.

If the join fails then the client will attempt to reconnect.

Implementation

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

  if (_handshakeGate.inProgress) {
    // already under connection
    return _handshakeGate.pending!;
  }

  try {
    await tryCatchIgnore(() async {
      await _transport?.close();
    });

    _transport = _transportFactory();
    _outboundQueue = OutboundQueue(
      onSend: (data) => _transport!.send(data),
      maxBufferSize: _maxBufferSize,
    );

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

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

    final connected = await _performJoin();
    if (connected) {
      // Seed liveness so a fresh connection is not immediately judged dead.
      _lastPongAt = DateTime.now();
      _startPingTimer();
      _updateConnectionStatus(ConnectionStatus.connected);
      for (final plugin in plugins) {
        plugin.onConnected();
      }
    }

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