diff --git a/contentcuration/contentcuration/frontend/shared/data/serverSync.js b/contentcuration/contentcuration/frontend/shared/data/serverSync.js index e8816ae375..6887cc7c3a 100644 --- a/contentcuration/contentcuration/frontend/shared/data/serverSync.js +++ b/contentcuration/contentcuration/frontend/shared/data/serverSync.js @@ -28,6 +28,9 @@ import urls from 'shared/urls'; // change being registered, sync changes! const SYNC_IF_NO_CHANGES_FOR = 0.5; +// Set ping interval to 25 seconds +const WEBSOCKET_PING_INTERVAL = 25000; + let socket; // Flag to check if a sync is currently active. let syncActive = false; @@ -260,11 +263,13 @@ async function WebsocketSendChanges() { // in order to still call our change cleanup code. if (changes.length) { requestPayload.changes = changes; + //set ping to false to reset ping timmer socket.send( JSON.stringify({ payload: requestPayload, }) ); + debouncePingMessage(); } } syncActive = false; @@ -370,6 +375,15 @@ const debouncedSyncChanges = debounce(() => { } }, SYNC_IF_NO_CHANGES_FOR * 1000); +const debouncePingMessage = debounce(() => { + socket.send( + JSON.stringify({ + ping: 'PING!', + }) + ); + debouncePingMessage(); +}, WEBSOCKET_PING_INTERVAL); + if (process.env.NODE_ENV !== 'production' && typeof window !== 'undefined') { window.forceServerSync = forceServerSync; } @@ -432,6 +446,9 @@ export function startSyncing() { console.log('Websocket connected'); }); + //Keep Pinging the websocket connection to keep connection alive + debouncePingMessage(); + // Listen for any errors due to which connection may be closed. socket.addEventListener('error', event => { console.log('WebSocket error: ', event); diff --git a/contentcuration/contentcuration/viewsets/websockets/consumers.py b/contentcuration/contentcuration/viewsets/websockets/consumers.py index 722281be12..b3579cdd70 100644 --- a/contentcuration/contentcuration/viewsets/websockets/consumers.py +++ b/contentcuration/contentcuration/viewsets/websockets/consumers.py @@ -84,6 +84,14 @@ def receive(self, text_data): from contentcuration.models import Channel from contentcuration.tasks import apply_channel_changes_task from contentcuration.tasks import apply_user_changes_task + + #If the message is PING message then just reply to keep connection alive + data = json.loads(text_data) + if "ping" in data: + self.send(json.dumps({ + 'response': "PONG!" + })) + return response_payload = { "disallowed": [],