WebSockets provide a full-duplex communication channel over a single TCP connection, enabling real-time data exchange between a client and server. Unlike HTTP, which is request/response-based, WebSockets stay open and allow both parties to send messages freely.
ws://
or wss://
(secured)The most popular WebSocket library for Node.js is ws. Install it using npm:
npm install ws
Other libraries include:
socket.io
– adds fallback transport and more abstractionuWebSockets.js
– ultra-fast alternativeHere’s how to create a simple WebSocket server using the ws module:
// server.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
ws.send('You said: ' + message);
});
ws.send('Hello from server!');
});
In the browser or Node.js:
// In browser console
const socket = new WebSocket('ws://localhost:8080');
socket.onmessage = (event) => console.log('Server:', event.data);
socket.onopen = () => socket.send('Hello Server!');
// In Node.js client
const WebSocket = require('ws');
const socket = new WebSocket('ws://localhost:8080');
socket.on('open', () => socket.send('Hello Server!'));
socket.on('message', data => console.log(`Received: ${data}`));
To send messages to all connected clients:
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send('Broadcast message');
}
});
Handle closed connections using the close
event:
ws.on('close', () => {
console.log('Client disconnected');
});
To use WSS (WebSocket Secure), use HTTPS and provide SSL credentials:
const https = require('https');
const fs = require('fs');
const WebSocket = require('ws');
const server = https.createServer({
cert: fs.readFileSync('cert.pem'),
key: fs.readFileSync('key.pem')
});
const wss = new WebSocket.Server({ server });
server.listen(8443);
Integrate WebSockets into an Express server:
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', ws => {
ws.send('Connected to Express + WS server');
});
server.listen(3000);
Feature | ws | socket.io |
---|---|---|
Protocol | WebSocket | Custom + fallback |
Ease of use | Manual | Higher abstraction |
Fallback (polling) | ❌ | ✅ |
Community | Medium | Large |
Helpful tools for debugging WebSocket applications:
wscat
– CLI WebSocket clientnpm install -g wscat
wscat -c ws://localhost:8080