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;
  }

  // The relay has already refused this build. Connecting again would only
  // earn the same refusal.
  if (isUnsupported) {
    return false;
  }

  if (handshake.inProgress) {
    // already under connection
    return handshake.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;
  }
}