connect method

Future<void> connect()

Connects to the WebSocket server.

Implementation

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

  _updateState(WebSocketState.connecting);
  _connectionStartTime = DateTime.now();

  try {
    // Set connection timeout
    _connectionTimer = Timer(config.connectionTimeout, () {
      if (_state == WebSocketState.connecting) {
        _handleConnectionFailure('Connection timeout');
      }
    });

    // Create WebSocket connection with headers and protocols
    final uri = Uri.parse(config.url);

    // Use platform-specific helper for cross-platform compatibility
    // Native platforms support headers, web platform has limitations
    if (config.headers.isNotEmpty || config.protocols.isNotEmpty) {
      _channel = platform.PlatformWebSocketHelper.connect(
        uri,
        protocols: config.protocols.isNotEmpty ? config.protocols : null,
        headers: config.headers.isNotEmpty ? config.headers : null,
      );
    } else {
      _channel = WebSocketChannel.connect(uri);
    }

    // Listen for messages
    _channel!.stream.listen(
      _handleIncomingMessage,
      onError: _handleError,
      onDone: _handleConnectionClosed,
    );

    // Wait for connection to be established
    await _waitForConnection();

    // Start heartbeat if enabled
    if (config.enableHeartbeat) {
      _startHeartbeat();
    }

    _updateState(WebSocketState.connected);
    _eventController.add(WebSocketEvent.connected());
  } catch (e) {
    _handleConnectionFailure('Connection failed: $e');
  }
}