I build a MERN stack chat app with socket.io. it works fine locally. the problem is coming after deployment. socket.io won't work because of load balancer. the load balancer tries to change the current server with another free and near server. in socket.io new user id is generated when the user join the chat. but when the server changes it forget the previous user id and generate a new one. in this way real time chat won't happen.
There is one way I heard before, using socket.io/sticky but I don't know how to use it with express.js.
i need you guys to change this node js code to express equivalent
const cluster = require("cluster");
const http = require("http");
const { Server } = require("socket.io");
const numCPUs = require("os").cpus().length;
const { setupMaster, setupWorker } = require("@socket.io/sticky");
const { createAdapter, setupPrimary } = require("@socket.io/cluster-adapter");
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
const httpServer = http.createServer();
setupMaster(httpServer, {
loadBalancingMethod: "least-connection", // either "random", "round-robin" or "least-connection"
});
setupPrimary();
httpServer.listen(3000);
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on("exit", (worker) => {
console.log(`Worker ${worker.process.pid} died`);
cluster.fork();
});
} else {
console.log(`Worker ${process.pid} started`);
const httpServer = http.createServer();
const io = new Server(httpServer);
io.adapter(createAdapter());
setupWorker(io);
io.on("connection", (socket) => {
/* ... */
});
}
it might not be only socket.io/sticky if you have any other solution let me know.