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 d210a27 commit 9bc3e34
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,24 @@ import { log } from "./log.js";

const wsServer = new WebSocketServer({ port: 8080 });

const wsConnections: WebSocket[] = [];
const clients: WebSocket[] = [];

let updateTimer: NodeJS.Timer | null = null;

const sendUpdate = () => {
const now = new Date();
const message = JSON.stringify({
time: now.toISOString(),
});

clients.forEach((sock) => sock.send(message));
};

// 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) {
if (clients.length && !updateTimer) {
updateTimer = setInterval(sendUpdate, 250);
} else if (!clients.length && updateTimer) {
clearInterval(updateTimer);
updateTimer = null;
} else {
Expand All @@ -24,14 +29,14 @@ const setOrClearInterval = () => {
};

wsServer.on("connection", (wsSocket) => {
wsConnections.push(wsSocket);
clients.push(wsSocket);
setOrClearInterval();

wsSocket.on("error", log.error);

wsSocket.on("close", () => {
const index = wsConnections.indexOf(wsSocket);
if (index > -1) wsConnections.splice(index, 1);
const index = clients.indexOf(wsSocket);
if (index > -1) clients.splice(index, 1);
setOrClearInterval();
});

Expand Down

0 comments on commit 9bc3e34

Please sign in to comment.