Update gitignore
This commit is contained in:
commit
9e0ddb8182
32 changed files with 3863 additions and 0 deletions
26
src/ws.js
Normal file
26
src/ws.js
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
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 };
|
||||
Loading…
Add table
Add a link
Reference in a new issue