This commit is contained in:
pradeepkumar
2026-03-28 02:21:36 +05:30
parent 40410c9972
commit 5909b7bf97
3 changed files with 70 additions and 52 deletions

View File

@@ -84,26 +84,34 @@ class SocketService {
_log.i('Socket connected: ${_socket!.id}');
_isConnected = true;
_connectionController.add(true);
// Reset reconnect counter after connection stays stable for 5 seconds
Future.delayed(const Duration(seconds: 5), () {
if (_isConnected) _reconnectAttempts = 0;
});
});
_socket!.onDisconnect((reason) {
_log.w('Socket disconnected: $reason');
final wasConnected = _isConnected;
_isConnected = false;
_connectionController.add(false);
// Only attempt reconnect for server-initiated disconnects, not transport issues
if (reason == 'io server disconnect' && !_intentionalDisconnect) {
if (_reconnectAttempts < _maxReconnectAttempts) {
_reconnectAttempts++;
_log.w('Server rejected connection (attempt $_reconnectAttempts/$_maxReconnectAttempts) - refreshing token...');
_reconnectWithFreshToken();
} else {
_log.e('Max reconnect attempts reached - giving up. Check backend logs for rejection reason.');
_reconnectAttempts = 0; // Reset for future manual reconnects
// If we were stably connected (not a connect-then-immediate-disconnect),
// reset the counter — this is a new disconnection event
if (wasConnected) {
// Check: was the connection stable? (connected for more than 2 seconds)
// If not, it's a repeated rejection — increment counter
}
if (_reconnectAttempts >= _maxReconnectAttempts) {
_log.e('Max reconnect attempts ($_maxReconnectAttempts) reached. Server keeps rejecting. Giving up.');
_reconnectAttempts = 0;
return;
}
_reconnectAttempts++;
_log.w('Server rejected (attempt $_reconnectAttempts/$_maxReconnectAttempts)');
_reconnectWithFreshToken();
} else if (reason == 'ping timeout' || reason == 'transport close') {
// Network issue — socket.io auto-reconnects, reset counter
_reconnectAttempts = 0;
}
});
@@ -183,50 +191,32 @@ class SocketService {
Future<void> _reconnectWithFreshToken() async {
// Wait with exponential backoff
final delay = Duration(seconds: _reconnectAttempts * 2);
_log.i('Waiting ${delay.inSeconds}s before reconnect attempt...');
final delay = Duration(seconds: _reconnectAttempts * 2 + 1);
_log.i('Waiting ${delay.inSeconds}s before reconnect attempt $_reconnectAttempts/$_maxReconnectAttempts...');
await Future.delayed(delay);
final token = await SecureStorage.getAccessToken();
if (token == null) {
_log.w('No access token available for socket reconnection');
// Try to get a fresh token
try {
final dio = ApiClient.instance.dio;
await dio.get('/auth/me');
} catch (_) {}
final freshToken = await SecureStorage.getAccessToken();
if (freshToken == null) {
_log.w('No token available, giving up');
return;
}
// If token hasn't changed, try triggering a refresh via a lightweight API call
if (token == _currentToken) {
_log.i('Token unchanged, triggering refresh via /auth/me...');
try {
final dio = ApiClient.instance.dio;
await dio.get('/auth/me');
final refreshedToken = await SecureStorage.getAccessToken();
if (refreshedToken == null || refreshedToken == _currentToken) {
_log.w('Token refresh did not produce a new token');
// Still try reconnecting — token might be valid but socket had a glitch
} else {
_log.i('Got fresh token after refresh');
}
} catch (e) {
_log.e('Token refresh failed: $e');
// Still try reconnecting with existing token
}
_log.i('Reconnecting socket with token...');
_currentToken = freshToken;
// Update auth on existing socket and reconnect (don't recreate)
if (_socket != null) {
_socket!.io.options?['auth'] = {'token': freshToken};
_socket!.connect();
} else {
await connect();
}
// Get the latest token (may have been refreshed)
final freshToken = await SecureStorage.getAccessToken();
if (freshToken == null) return;
_log.i('Reconnecting socket with fresh token...');
// Full reconnect — dispose old socket and create new one
_socket?.disconnect();
_socket?.dispose();
_socket = null;
_isConnected = false;
_currentToken = null;
// Small delay before reconnecting
await Future.delayed(const Duration(milliseconds: 500));
await connect();
}
/// Ensure socket is connected — reconnect if needed.