close method
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);
}
}