From d210a27a37cc5296896be60ce6baf25d52669d65 Mon Sep 17 00:00:00 2001 From: Tore Sinding Bekkedal Date: Wed, 5 Jul 2023 04:56:59 +0300 Subject: [PATCH] Flesh out websockets a little more --- src/api.ts | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/api.ts b/src/api.ts index f0cb6a6..382a93f 100644 --- a/src/api.ts +++ b/src/api.ts @@ -5,14 +5,37 @@ const wsServer = new WebSocketServer({ port: 8080 }); const wsConnections: WebSocket[] = []; +let updateTimer: NodeJS.Timer | null = null; + +// If any clients are connected, send an update every 250 ms. +const setOrClearInterval = () => { + if (wsConnections.length && !updateTimer) { + updateTimer = setInterval(() => { + wsConnections.forEach((wsSocket) => { + wsSocket.send("something"); + }); + }, 250); + } else if (!wsConnections.length && updateTimer) { + clearInterval(updateTimer); + updateTimer = null; + } else { + log.warn("unexpected state in setOrClearInterval"); + } +}; + wsServer.on("connection", (wsSocket) => { wsConnections.push(wsSocket); + setOrClearInterval(); wsSocket.on("error", log.error); + wsSocket.on("close", () => { + const index = wsConnections.indexOf(wsSocket); + if (index > -1) wsConnections.splice(index, 1); + setOrClearInterval(); + }); + wsSocket.on("message", (data) => { log.warn(`Received message ${data} on read-only socket`); }); - - wsSocket.send("something"); });