server/lib/ws.js
2025-03-31 14:17:29 +02:00

36 lines
766 B
JavaScript

import { WebSocketServer } from 'ws';
let wss;
let connections = [];
export function init(cfg, db) {
wss = new WebSocketServer(cfg);
console.log(cfg);
wss.on('connection', ws => {
console.log('new connection')
connections.push(ws);
ws.on('error', console.error);
ws.on('close', (e) => {
connections.splice(connections.indexOf(ws), 1);
});
ws.on('message', (data, isBinary) => {
try {
let message = JSON.parse(data);
switch (message.action) {
case "set":
break;
case "subscribe":
break;
default:
throw 'invalid action "' + message.action + '"';
}
} catch (e) {
console.error(e);
}
});
});
return wss;
}