diff options
author | Devaev Maxim <[email protected]> | 2018-07-14 05:25:15 +0300 |
---|---|---|
committer | Devaev Maxim <[email protected]> | 2018-07-14 05:25:15 +0300 |
commit | 2b8d6b215cf61cd04d21d7d1931985eeb36cccb3 (patch) | |
tree | 1416f16895817597b1322df5df84839c829c933f /kvmd/web | |
parent | b2f57590b6ff70f5100cdc8b1de70bfe093c0357 (diff) |
client-side ping-pong
Diffstat (limited to 'kvmd/web')
-rw-r--r-- | kvmd/web/js/kvmd.js | 27 |
1 files changed, 25 insertions, 2 deletions
diff --git a/kvmd/web/js/kvmd.js b/kvmd/web/js/kvmd.js index 6f254a29..e6d00f31 100644 --- a/kvmd/web/js/kvmd.js +++ b/kvmd/web/js/kvmd.js @@ -11,13 +11,16 @@ function __startSessionPoller() { ws.onopen = function(event) { __installHidHandlers(ws); __setSessionStatus(true); + __startSessionPoller.ping_server_timer = setInterval(() => __pingServer(ws), 2000); }; ws.onmessage = function(event) { // console.log("KVMD:", event.data); event = JSON.parse(event.data); if (event.msg_type == "event") { - if (event.msg.event == "atx_state") { + if (event.msg.event == "pong") { + __pingServer.missed_heartbeats = 0; + } else if (event.msg.event == "atx_state") { leds = event.msg.event_attrs.leds; document.getElementById("atx-power-led").className = (leds.power ? "led-on" : "led-off"); document.getElementById("atx-hdd-led").className = (leds.hdd ? "led-busy" : "led-off"); @@ -26,6 +29,9 @@ function __startSessionPoller() { }; ws.onclose = function(event) { + if (__startSessionPoller.ping_server_timer) { + clearInterval(__startSessionPoller.ping_server_timer); + } __clearHidHandlers(); __setSessionStatus(false); document.getElementById("atx-power-led").className = "led-off"; @@ -38,6 +44,21 @@ function __startSessionPoller() { }; } +function __pingServer(ws) { + try { + __pingServer.missed_heartbeats++; + if (__pingServer.missed_heartbeats >= 5) { + throw new Error("Too many missed heartbeats"); + } + ws.send(JSON.stringify({"event_type": "ping"})); + } catch (err) { + __pingServer.missed_heartbeats = 0; + console.warn("Closing session:", err.message); + ws.close(); + } +} +__pingServer.missed_heartbeats = 0; + function __setSessionStatus(status) { var el_session_status = document.getElementById("session-status"); el_session_status.innerHTML = (status ? "Session active" : "Session closed, trying to reconnect..."); @@ -74,7 +95,9 @@ function __installHidHandlers(ws) { } function __clearHidHandlers() { - clearInterval(__installHidHandlers.mouse_move_timer); + if (__installHidHandlers.mouse_move_timer) { + clearInterval(__installHidHandlers.mouse_move_timer); + } document.onkeydown = null; document.onkeyup = null; |