initWebSocket method

Future<void> initWebSocket(
  1. String? sokcketApi,
  2. String? socketCookie
)

Initializes the WebSocket connection.

sokcketApi: The WebSocket server URL (e.g., wss://example.com/ws) socketCookie: Optional cookies for authentication (can be null)

Only the first call will establish the connection; subsequent calls are ignored if already connected.

Implementation

Future<void> initWebSocket(
    String? sokcketApi,
    String? socketCookie,
    ) async {
  if (_channel != null) {
    debugPrint("✅ WebSocket already initialized.");
    return;
  }

  try {
    // If cookies are provided, add them to the connection headers
    if (socketCookie != null && socketCookie.isNotEmpty) {
      _channel = IOWebSocketChannel.connect(Uri.parse(sokcketApi!), headers: {
        "Cookie": socketCookie,
      });
    } else {
      _channel = IOWebSocketChannel.connect(Uri.parse(sokcketApi!));
    }

    // Wait for the connection to be ready
    await _channel!.ready;
    debugPrint("🟢 WebSocket Connected!");

    // Use a broadcast stream so multiple listeners can subscribe
    _streamController = StreamController.broadcast();
    _streamController!.addStream(_channel!.stream);
  } catch (e, st) {
    debugPrint("❌ WebSocket Error: $e\nStacktrace: $st");
  }
}