connect method

Future<void> connect()

Explicitly initiates connection to the WebSocket server.

Safe to call repeatedly: if already connected or currently connecting, this method returns immediately without creating duplicate connections.

Implementation

Future<void> connect() async {
  if (_isDisposed) return;
  if (_socket != null ||
      _state == RealtimeConnectionState.connected ||
      _state == RealtimeConnectionState.connecting) {
    return;
  }

  _reconnectTimer?.cancel();
  _reconnectTimer = null;

  _updateState(
    _reconnectAttempts > 0
        ? RealtimeConnectionState.reconnecting
        : RealtimeConnectionState.connecting,
  );

  try {
    final ws = protocols != null && protocols!.isNotEmpty
        ? web.WebSocket(
            uri.toString(),
            protocols!.map((p) => p.toJS).toList().toJS,
          )
        : web.WebSocket(uri.toString());

    _socket = ws;

    ws.onopen = ((web.Event _) {
      if (_isDisposed || ws != _socket) {
        try {
          ws.close();
        } catch (_) {}
        return;
      }
      _reconnectAttempts = 0;
      _updateState(RealtimeConnectionState.connected);
      _startPingTimer();
      _resubscribeAll();
    }).toJS;

    ws.onmessage = ((web.MessageEvent event) {
      if (_isDisposed || ws != _socket) return;
      _onMessageReceived(event);
    }).toJS;

    ws.onerror = ((web.Event _) {
      if (_isDisposed || ws != _socket) return;
      _handleDisconnect(ws);
    }).toJS;

    ws.onclose = ((web.CloseEvent _) {
      if (_isDisposed || ws != _socket) return;
      _handleDisconnect(ws);
    }).toJS;
  } catch (_) {
    _handleDisconnect(null);
  }
}