Instructions to Integrate Express with WebSockets in Node.
js
In this project, you need to add Express to your existing WebSocket server so that you can serve HTTP
routes along with WebSockets. Follow these steps to properly integrate Express:
🛠 Steps to Modify server.js
1️⃣ Install Express
Run the following command to install Express:
sh
CopiarEditar
npm install express
2️⃣ Modify server.js to Include Express
• Import express and http modules.
• Create an Express app and an HTTP server.
• Attach the WebSocket server to the HTTP server.
3️⃣ Update the WebSocket Server to Use the HTTP Server
• Instead of binding WebSockets directly to a port, use the same port as Express.
📌 Updated Code with Express
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 });
let count = 0;
// Serve a basic route
app.get('/', (req, res) => {
res.send('WebSocket Server Running with Express!');
});
wss.on('connection', function connection(ws) {
ws.send(JSON.stringify({ type: 'count', data: count }));
ws.on('message', function incoming(message) {
const data = JSON.parse(message);
if (data.type === 'increment') {
count += data.value;
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type: 'count', data: count }));
}
});
} else if (data.type === 'reset') {
count = 0;
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type: 'count', data: count }));
}
});
}
});
});
// Start the server on port 9090
server.listen(9090, '10.38.33.29', () => {
console.log('Server is running on http://10.38.33.29:9090');
});
🚀 What You Just Did
✅ Integrated Express: Now you can handle HTTP requests along with WebSockets.
✅ Shared the Same Port: Express and WebSocket server both run on port 9090.
✅ Basic Route (/): You can visit http://10.38.33.29:9090/ to check if the server is
running.