The easiest way to use WebSocket connections is directrly through Node's ws module.
Install (why bufferutil and utf-8-validate matter):
npm install --save ws bufferutil utf-8-validate
Initialize a server:
const wss = new Server({ server });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('close', () => console.log('Client disconnected'));
});
Broadcast updates to clients:
setInterval(() => {
wss.clients.forEach((client) => {
client.send(new Date().toTimeString());
});
}, 1000);
References: