connect method

Future<void> connect()

Establishes WebSocket connection to the server

This method creates a WebSocket connection and sets up message handling. Connection state will be emitted through the onConnectionState stream.

Implementation

Future<void> connect() async {
  if (isConnected || isConnecting) {
    if (isConnected) return;
    await Future.delayed(const Duration(milliseconds: 100));
    if (isConnected) return;
  }

  _setConnectionState(WebSocketConnectionState.connecting);

  try {
    // Reuse session ID for reconnections to prevent connection spam
    _currentSessionId ??= _random.nextInt(999999);
    final sessionId = _currentSessionId!;

    final serverUri = Uri.parse(serverUrl);
    final uri = Uri(
        scheme: serverUri.scheme,
        host: serverUri.host,
        port: serverUri.port == 0
            ? (serverUri.scheme == 'wss' ? 443 : 80)
            : serverUri.port,
        path: '/ws/$sessionId',
        queryParameters: {'is_audio': 'true'});

    _channel = WebSocketChannel.connect(uri);

    _channel!.stream.listen(
      _handleMessage,
      onError: _handleError,
      onDone: _handleDisconnect,
    );

    await _channel!.ready.timeout(connectionTimeout);
    await Future.delayed(const Duration(milliseconds: 500));

    _setConnectionState(WebSocketConnectionState.connected);
  } catch (e) {
    _setConnectionState(WebSocketConnectionState.error);
    _errorSubject.add('Connection failed: $e');
    throw Exception('Failed to connect to server: $e');
  }
}