Skip to content

Commit

Permalink
Flesh out websockets a little more
Browse files Browse the repository at this point in the history
  • Loading branch information
toresbe committed Jul 5, 2023
1 parent ed1e7e0 commit d210a27
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});

0 comments on commit d210a27

Please sign in to comment.