connectToSocket method
void
connectToSocket()
Implementation
void connectToSocket() {
print('connect entered');
if (isSocketConnected) {
print('Socket is already connected. Skipping connection.');
return;
}
socket = io.io(socketUrl, <String, dynamic>{
'transports': ['websocket'],
'autoConnect': false,
'forceNew': true,
'reconnection': true,
'reconnectionAttempts': 5,
'reconnectionDelay': 2000,
'query': {'x-client-id': userId, 'appId': appId},
});
socket.connect();
socket.onConnect((_) {
print('Connected to the socket server');
isSocketConnected = true;
});
socket.onDisconnect((_) {
dispose();
isSocketConnected = false;
print('Disconnected from the socket server');
});
// Ensure no duplicate listener
socket.off(RECEIVE_POPUP_MOBILE_EVENT);
socket.on(RECEIVE_POPUP_MOBILE_EVENT, (json) {
handlePopupReceived(json);
});
socket.off(CANCEL_THIS_POPUP_EVENT);
socket.on(CANCEL_THIS_POPUP_EVENT, (data) {
var canceledIds = data['canceledIds'];
print("Cancel signal received: $canceledIds");
if (canceledIds is List) {
for (var canceledId in canceledIds) {
if (shownPopupIds.contains(canceledId)) {
shownPopupIds.remove(canceledId);
if (Navigator.canPop(context)) {
Navigator.pop(context);
} else {
print("No active route to pop for context.");
}
print("Popup with ID $canceledId is canceled. Closing...");
}
}
} else {
print("Error: canceledIds is not a list");
}
});
socket.on(Event_RECONNECT, (attempt) {
print("Reconnected after $attempt attempts");
});
socket.on(Event_RECONNECT_ERROR, (error) {
print("Reconnection error! $error");
});
}