Library ws: WebSocket for Node.js
The ws library is a simple, fast, and thoroughly tested implementation of the WebSocket protocol for Node.js. It is the de facto standard for creating real-time applications (chats, online games, notifications, collaborative editing) on the server-side JavaScript. Unlike the built-in http module, ws provides full bidirectional communication between client and server without constant HTTP requests.
Key Features
- Full support for RFC 6455 protocol — works with all modern browsers.
- High performance — minimal memory consumption and low latency.
- Simple API — create a server and client in a few lines of code.
- Extension support — data compression (permessage-deflate).
- Integration with HTTP server — can share a port with Express or other frameworks.
- Automatic reconnection — built-in mechanisms for the client.
Installation
Installation via npm:
npm install wsAfter installation, the library is ready to use.
Creating a WebSocket Server
Let's create a simple server that accepts connections and sends a welcome message:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) { console.log('New client connected');
// Send a message to the client ws.send('Welcome to the WebSocket server!');
// Handle incoming messages ws.on('message', function incoming(message) { console.log('Received: %s', message); // Send back (echo) ws.send('Echo: ' + message); });
// Handle connection close ws.on('close', function() { console.log('Client disconnected'); });});
console.log('WebSocket server started on ws://localhost:8080');Creating a WebSocket Client
The client connects to the server, sends a message, and receives a response:
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:8080');
ws.on('open', function open() { console.log('Connection established'); ws.send('Hello, server!');});
ws.on('message', function incoming(data) { console.log('Response from server: %s', data); ws.close();});
ws.on('close', function() { console.log('Connection closed');});
ws.on('error', function error(err) { console.error('Error:', err.message);});Working with JSON and Multiple Clients
A real-world example — a chat server that broadcasts messages to all connected clients:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws, req) { console.log('Client connected. Total clients:', wss.clients.size);
ws.on('message', function incoming(message) { // Parse JSON let data; try { data = JSON.parse(message); } catch (e) { ws.send(JSON.stringify({ error: 'Invalid JSON' })); return; }
// Broadcast to everyone except the sender wss.clients.forEach(function each(client) { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(JSON.stringify({ username: data.username, text: data.text, timestamp: Date.now() })); } }); });
ws.send(JSON.stringify({ system: 'Welcome to the chat!' }));});The client can send JSON:
ws.send(JSON.stringify({ username: 'Alice', text: 'Hello everyone!' }));