diff --git a/lib/features/messaging/data/socket_service.dart b/lib/features/messaging/data/socket_service.dart index 4f410f5..c81f6fe 100644 --- a/lib/features/messaging/data/socket_service.dart +++ b/lib/features/messaging/data/socket_service.dart @@ -20,7 +20,6 @@ class SocketService { io.Socket? _socket; bool _isConnected = false; bool _intentionalDisconnect = false; - bool _isReconnecting = false; int _reconnectAttempts = 0; static const _maxReconnectAttempts = 3; String? _currentToken; @@ -84,9 +83,11 @@ class SocketService { _socket!.onConnect((_) { _log.i('Socket connected: ${_socket!.id}'); _isConnected = true; - _reconnectAttempts = 0; // Reset on successful connect - _isReconnecting = false; _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) { @@ -94,13 +95,14 @@ class SocketService { _isConnected = false; _connectionController.add(false); - if (reason == 'io server disconnect' && !_intentionalDisconnect && !_isReconnecting) { + 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'); + _log.e('Max reconnect attempts reached - giving up. Check backend logs for rejection reason.'); + _reconnectAttempts = 0; // Reset for future manual reconnects } } }); @@ -180,7 +182,6 @@ class SocketService { } Future _reconnectWithFreshToken() async { - _isReconnecting = true; // Wait with exponential backoff final delay = Duration(seconds: _reconnectAttempts * 2); _log.i('Waiting ${delay.inSeconds}s before reconnect attempt...'); @@ -236,7 +237,6 @@ class SocketService { void disconnect() { _intentionalDisconnect = true; - _isReconnecting = false; _reconnectAttempts = 0; _socket?.disconnect(); _socket?.dispose();