connect method

Future<void> connect()

Implementation

Future<void> connect() async {
  try {
    await _ws?.close(WebSocketStatus.goingAway);
    onConnecting?.call();
    _ws = await WebSocket.connect(
      uri.toString(),
      headers: headers,
    );
    _ws!.pingInterval = const Duration(seconds: 10);

    if (_ws?.readyState == WebSocket.open) {
      _isConnected = true;
      _subscription = _ws!.listen(
        (event) => _onReceive(event, onReceive),
        onDone: _onDone,
        onError: _onError,
        cancelOnError: true,
      );
      onConnected?.call();
    } else {
      debugPrint('[!]Connection Denied');
      _isConnected = false;
      reconnect();
    }
  } on Exception catch (error) {
    debugPrint('[!]Error -- ${error.toString()}');
    onConnectionFail?.call(error);
    reconnect();
  }
}