1. Introduction to WebSockets in Node.js

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.

2. Installing WebSocket Libraries

The most popular WebSocket library for Node.js is ws. Install it using npm:

npm install ws

Other libraries include:

3. Creating a Basic WebSocket Server

Here’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!');
});
			

4. Creating a WebSocket Client

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}`));
			

5. Broadcasting Messages

To send messages to all connected clients:


wss.clients.forEach(function each(client) {
	if (client.readyState === WebSocket.OPEN) {
		client.send('Broadcast message');
	}
});
			

6. Handling Disconnections

Handle closed connections using the close event:


ws.on('close', () => {
	console.log('Client disconnected');
});
			

7. Securing WebSockets (WSS)

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);
			

8. Using WebSockets with Express

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);
			

9. Alternatives: Socket.IO vs ws

Featurewssocket.io
ProtocolWebSocketCustom + fallback
Ease of useManualHigher abstraction
Fallback (polling)
CommunityMediumLarge

10. Debugging and Tools

Helpful tools for debugging WebSocket applications:

npm install -g wscat
wscat -c ws://localhost:8080

11. Real-World Use Cases