Skip to content

Latest commit

 

History

History
30 lines (24 loc) · 756 Bytes

use-web-sockets.md

File metadata and controls

30 lines (24 loc) · 756 Bytes

How to use WebSocket connections with Node.js

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: