close method

void close(
  1. ESocketCloseCode code, {
  2. bool reconnect = false,
})

Closes the underlying socket connection, and clears all the event listeners and subscriptions to events as well as any other information related to the connection. @param code { ESocketCloseCode }

Implementation

void close(ESocketCloseCode code, {bool reconnect = false}) {
  final reason = socketCloseReason[code];
  final closeCode = code.value;

  if ((closeCode >= 3000 && closeCode <= 4999) ||
      closeCode == 1000 ||
      (closeCode == 1001 && !reconnect)) {
    logger.i('πŸ”Œ Closing the connection, $code $reason');
    _ws?.innerWebSocket?.close(closeCode, reason);

    _ws = null;

    token = null;

    _endpoint = null;

    emit('token-updated', null);

    connectionState = ConnectionState.closed;

    emit('closed', code);

    logger.i('πŸ”Œ WebSocket Connection closed');

    return;
  }
  _subscribedMap.clear();

  _ws?.innerWebSocket?.close();
  _ws = null;

  if (code == ESocketCloseCode.abnormalClosure || reconnect) {
    logger.i(
      'πŸ”Œ Socket Connection closed abnormally, reconnecting  | code: ${code.value} | reason: $reason',
    );

    if (_retryCount < 7) {
      final delay = 2 ^ _retryCount * 1000;

      Timer(Duration(milliseconds: min(delay, 20000)), () {
        if (token != null) {
          try {
            logger.i('πŸ”” Trying to reconnect, Attempt: $_retryCount');
            connectionState = ConnectionState.reconnecting;

            emit('reconnecting');
            if (token != null) {
              connect(token!).then((_) {
                if (_retryCount > 0) {
                  emit('reconnected');
                }

                _retryCount = 0;
              }).catchError((e) {
                if (_retryCount == 7) {
                  logger.e('All Reconnection Attempt failed');
                }
              });
            }
          } catch (err) {
            logger.e('Reconnection Attempt $_retryCount failed | err: $err');
          }
        }
      });
      _retryCount++;
    } else {
      logger.e('πŸ”΄ Socket connection closed abnormally, reconnecting failed');

      close(ESocketCloseCode.connectionExpired);
    }
  } else {
    logger.i(
      'πŸ”Œ Socket Connection closed | code: ${code.value} | reason: $reason',
    );

    connectionState = ConnectionState.closed;

    emit('closed', code);
  }
}