connect method

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

Establishes a WebSocket connection

Implementation

@override
Future<void> connect() async {
  if (_currentState == WebSocketState.connecting ||
      _currentState == WebSocketState.connected) {
    return;
  }

  _updateState(WebSocketState.connecting);

  try {
    final uri = Uri.parse(_config.url);

    // Set up connection timeout
    _connectionTimeoutTimer = Timer(_config.connectionTimeout, () {
      if (_currentState == WebSocketState.connecting) {
        _handleError(
          TimeoutException('Connection timeout', _config.connectionTimeout),
        );
      }
    });

    if (isWeb) {
      _channel = WebSocketChannel.connect(uri, protocols: _config.protocols);
    } else {
      _channel = IOWebSocketChannel.connect(
        uri,
        protocols: _config.protocols,
        headers: _config.headers,
        customClient: _config.httpClient,
        pingInterval: _config.pingInterval,
        connectTimeout: _config.connectionTimeout,
      );
    }

    // Listen to the channel stream
    _channelSubscription = _channel!.stream.listen(
      _handleMessage,
      onError: _handleError,
      onDone: _handleDone,
    );

    // Wait for connection to be established
    await _channel!.ready;
    _connectionTimeoutTimer?.cancel();
    _updateState(WebSocketState.connected);
  } catch (error) {
    _connectionTimeoutTimer?.cancel();
    _updateState(WebSocketState.error);
    _errorController.add(error);
    rethrow;
  }
}