connect method

Future<void> connect()

Connects to the WebSocket server and starts listening for messages.

Throws a FreeFireSocketException if connection fails or if listen is false.

Implementation

Future<void> connect() async {
  try {
    if (_socketConfig.listen) {
      _channel = IOWebSocketChannel.connect(_socketConfig.ws);
      _channel?.stream.listen((json) async {
        if (_socketConfig.persistStream) {
          var old = _prefs?.getStringList(_socketConfig.persistanceKey) ?? [];
          old.add(json);
          var p = await _prefs?.setStringList(_socketConfig.persistanceKey, old);
          if (p == false) {
            log('Persistence Failed', name: 'Persisting message');
          }
        }
        _streamController.add(json as T);
      });
    } else {
      throw FreeFireSocketException('Socket Config value [listen] is set to false');
    }
  } on SocketException catch (e) {
    throw FreeFireSocketException(e.message);
  } catch (e) {
    throw FreeFireSocketException('Socket Config value [listen] is set to false');
  }
}