Q40: How do you combine Express with WebSockets (Socket.io) on a shared port?
Express handles standard HTTP requests, while Socket.io hooks into the shared native http.Server instance to manage WebSocket upgrades.
Sharing HTTP Server with Socket.io
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app); // Wrap Express in HTTP server
const io = new Server(server); // Attach Socket.io
io.on('connection', (socket) => {
console.log('Client connected:', socket.id);
});
server.listen(3000); // Listen on unified HTTP/WebSocket port💡 Wrapping Express in a raw http.Server allows Socket.io and Express to share port 3000.
Key Takeaways
- Pass the raw
http.Serverinstance wrapping Express into Socket.io. - Allows both REST API routes and real-time WebSocket channels to share a single port.