From 9e7d0cdfeb9ba8481a16067e3e3737f01646a85f Mon Sep 17 00:00:00 2001 From: liamcottle Date: Sat, 8 Feb 2025 11:53:10 +1300 Subject: [PATCH] add ping pong to make sure websocket connection doesn't go stale --- meshchat.py | 8 +++++++- src/frontend/js/WebSocketConnection.js | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/meshchat.py b/meshchat.py index e3f9bb2..4d4b984 100644 --- a/meshchat.py +++ b/meshchat.py @@ -2081,8 +2081,14 @@ class ReticulumMeshChat: # get type from client data _type = data["type"] + # handle ping + if _type == "ping": + AsyncUtils.run_async(client.send_str(json.dumps({ + "type": "pong", + }))) + # handle updating config - if _type == "config.set": + elif _type == "config.set": # get config from websocket config = data["config"] diff --git a/src/frontend/js/WebSocketConnection.js b/src/frontend/js/WebSocketConnection.js index d4622b8..f379213 100644 --- a/src/frontend/js/WebSocketConnection.js +++ b/src/frontend/js/WebSocketConnection.js @@ -3,8 +3,18 @@ import mitt from 'mitt'; class WebSocketConnection { constructor() { + this.emitter = mitt(); this.reconnect(); + + /** + * ping websocket server every 30 seconds + * this helps to prevent the underlying tcp connection from going stale when there's no traffic for a long time + */ + setInterval(() => { + this.ping(); + }, 30000); + } // add event listener @@ -47,6 +57,16 @@ class WebSocketConnection { } } + ping() { + try { + this.send(JSON.stringify({ + "type": "ping", + })); + } catch(e) { + // ignore error + } + } + } export default new WebSocketConnection();