Express.js and WebSockets
WebSockets provide a way to open a persistent connection between a client and server, allowing for real-time, bidirectional communication. This guide covers key concepts, examples, and best practices for using WebSockets in Express.js applications.
Key Concepts of WebSockets
- WebSocket: A protocol that provides full-duplex communication channels over a single TCP connection.
- Persistent Connection: WebSockets maintain an open connection between the client and server, allowing for continuous data exchange.
- Real-Time Communication: Enables instant communication between clients and servers.
Setting Up WebSockets
Integrate WebSockets with an Express.js server using the ws
library:
Example: Basic Setup
// Install the ws library
// npm install ws
// server.js
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 });
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
wss.on('connection', (ws) => {
console.log('A new client connected');
ws.on('message', (message) => {
console.log(`Received message: ${message}`);
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
// index.html
WebSocket Example
WebSocket Example