Real-time communication is a cornerstone of modern web applications, enabling functionalities like live updates, chat systems, notifications, and collaborative tools. Two popular techniques to implement real-time data transmission in Express.js are WebSocket and Server-Sent Events (SSE). This chapter will dive deep into both technologies, explaining their use cases, differences, implementations, and advanced strategies.
Real-time communication allows a server to push updates to a client without requiring the client to repeatedly request data. This is essential for applications like:
Aspect | HTTP (Request-Response) | WebSocket | SSE |
---|---|---|---|
Direction | Client → Server | Bi-directional | Server → Client |
Connection | New connection per request | Persistent | Persistent |
Protocol | HTTP | WebSocket | HTTP |
Complexity | Simple | Complex | Simple |
Use Case | Static APIs | Chat systems, games | Notifications, live updates |
WebSocket is a protocol that provides full-duplex communication between a client and server over a single TCP connection. It enables both the client and the server to send messages to each other simultaneously.
Server-Sent Events (SSE) is a simpler way to push updates from the server to the client using HTTP. Unlike WebSocket, SSE only allows unidirectional communication (server to client).
npm install express ws
const express = require('express');
const { WebSocketServer } = require('ws');
const app = express();
const PORT = 3000;
// HTTP Server
app.get('/', (req, res) => {
res.send('WebSocket with Express.js');
});
// WebSocket Server
const wss = new WebSocketServer({ noServer: true });
// WebSocket Connection
wss.on('connection', (ws) => {
console.log('Client connected');
// Listen for messages from the client
ws.on('message', (message) => {
console.log(`Received: ${message}`);
ws.send(`You said: ${message}`);
});
// Handle connection close
ws.on('close', () => {
console.log('Client disconnected');
});
});
// Upgrade HTTP to WebSocket
const server = app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
server.on('upgrade', (request, socket, head) => {
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
});
ws
library for WebSocket functionality.
const ws = new WebSocket('ws://localhost:3000');
ws.onopen = () => ws.send('Hello Server!');
ws.onmessage = (event) => console.log(`Server: ${event.data}`);
const express = require('express');
const app = express();
const PORT = 3000;
// SSE Endpoint
app.get('/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// Send initial event
res.write(`data: Connected to SSE\n\n`);
// Send periodic updates
const interval = setInterval(() => {
res.write(`data: ${new Date().toISOString()}\n\n`);
}, 1000);
// Cleanup on client disconnect
req.on('close', () => {
clearInterval(interval);
res.end();
});
});
// HTTP Server
app.get('/', (req, res) => {
res.send('SSE with Express.js');
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
res.write()
to send data.
const eventSource = new EventSource('http://localhost:3000/events');
eventSource.onmessage = (event) => {
console.log('New message:', event.data);
};
Feature | WebSocket | SSE |
---|---|---|
Communication | Bi-directional | Server to Client |
Complexity | Higher | Lower |
Browser Support | Needs polyfills for old browsers | Widely supported |
Connection Count | Optimized for fewer clients | Optimized for many clients |
Broadcast messages to all clients:
wss.on('connection', (ws) => {
ws.on('message', (message) => {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});
Send named events:
res.write(`event: customEvent\n`);
res.write(`data: Custom event data\n\n`);
Tools like Postman and browser-based WebSocket clients can help test WebSocket connections.
Browser developer tools (Network tab) show the stream of events.
WebSocket and Server-Sent Events (SSE) are powerful tools for implementing real-time features in web applications using Express.js. Choose the protocol based on your application’s requirements, and implement robust real-time systems to deliver a dynamic user experience. The examples and strategies provided here should equip you to handle real-time communication challenges effectively. Happy coding !❤️