typescriptintermediate

WebSocket Server with ws

Create a WebSocket server with connection tracking, heartbeat ping/pong, and typed message handling.

typescript
import { WebSocketServer, WebSocket } from 'ws';

const wss = new WebSocketServer({ port: 8080 });
const clients = new Set<WebSocket>();

wss.on('connection', (ws) => {
  clients.add(ws);
  console.log(`Client connected (${clients.size} total)`);

  ws.on('message', (raw) => {
    const msg = JSON.parse(raw.toString());
    // Broadcast to all other clients
    for (const client of clients) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify(msg));
      }
    }
  });

  ws.on('close', () => {
    clients.delete(ws);
  });

  // Heartbeat
  const interval = setInterval(() => {
    if (ws.readyState === WebSocket.OPEN) ws.ping();
  }, 30_000);
  ws.on('close', () => clearInterval(interval));
});

Use Cases

  • Chat applications
  • Live notifications
  • Real-time dashboards

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.