How do you implement a WebSocket server in Node.js using the `ws` library?
Answer
The ws library is the most popular bare-bones WebSocket server for Node.js. Install with npm install ws. Basic server setup: const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws, req) => { ws.on('message', (data) => { console.log('Received:', data.toString()); ws.send('Echo: ' + data); }); ws.on('close', () => console.log('Client disconnected')); ws.send('Welcome!'); }). To broadcast to all clients: wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) client.send(message); }). The ws library integrates with existing HTTP servers (Express, Fastify) by attaching to the server instance rather than creating its own port, enabling WebSocket and HTTP on the same port.
Previous
What triggers can break a WebSocket connection?
Next
What are Socket.IO rooms and namespaces?
More WebSockets & Real-time Questions
View all →- Intermediate What are Socket.IO rooms and namespaces?
- Intermediate How do you handle WebSocket reconnection logic?
- Intermediate What is the difference between Socket.IO and raw WebSockets?
- Intermediate How do you authenticate WebSocket connections?
- Intermediate How do WebSockets work behind a load balancer?