heystreamer/src/ws.js
2026-11-20 18:55:47 +01:00

26 lines
620 B
JavaScript

const { WebSocket } = require('ws');
const clients = new Set();
function init(wss) {
wss.on('connection', (ws) => {
clients.add(ws);
console.log(`[ws] Client connected — total: ${clients.size}`);
ws.on('close', () => {
clients.delete(ws);
console.log(`[ws] Client disconnected — total: ${clients.size}`);
});
ws.on('error', () => clients.delete(ws));
});
}
function broadcast(data) {
const msg = JSON.stringify(data);
for (const client of clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(msg);
}
}
}
module.exports = { init, broadcast };