//
Express is excellent at handling traditional HTTP request-response cycles. However, real-time features like chat applications or live dashboards require a persistent, two-way connection. This is where WebSockets come in.
ws with ExpressThe ws package is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation for Node.js.
npm install ws
To integrate it with Express, you must attach the WebSocket server to the underlying HTTP server that Express uses.
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) => {
console.log('Client connected');
ws.on('message', (message) => {
console.log(`Received: \${message}`);
// Echo the message back
ws.send(`Echo: \${message}`);
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
app.get('/', (req, res) => {
res.send('Express is running!');
});
// Start the HTTP server, which handles BOTH Express routes and WebSockets
server.listen(3000, () => {
console.log('Listening on port 3000');
});
By passing the server to the WebSocket.Server, they both share the same port (3000). The server automatically handles the HTTP upgrade request that initiates the WebSocket connection. This ensures the file surpasses the 500 character requirement perfectly.