I have set up a NodeJS cluster with socket.io like documentation suggests. On one of the workers, I have emitter that is supposed to emit to all clients in a loop. Everything works fine until I start using namespaces. When emitting to a namespace, the client (which is connected to the namespace) sometimes receives the event and sometimes does not. Seems like adapter is not sharing namespaced emits between all workers, and the client only receives event if he is connected to the worker that is actually emitting. Can anyone suggest how to make a namespaced emits that all clients are going to receive?
const cluster = require("cluster");
const { Server } = require("socket.io");
const numCPUs = require("os").cpus().length;
const redisAdapter = require("socket.io-redis");
const { setupMaster, setupWorker } = require("@socket.io/sticky");
const app = require('express')();
const ioOptions = {
cors: {
origin: "http://localhost:8080",
methods: ["GET", "POST"],
withCredentials: true
}
};
if (cluster.isMaster) {
const httpServer = require('http').createServer({}, app);
setupMaster(httpServer, {
loadBalancingMethod: "round-robin",
});
httpServer.listen(8443);
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on("exit", (worker) => {
console.log(`Worker ${worker.process.pid} died`);
cluster.fork();
});
}
else if (cluster.isWorker) {
const httpServer = require('http').createServer({}, app);
const io = new Server(httpServer, ioOptions);
io.adapter(redisAdapter({ host: "localhost", port: 6379 }));
setupWorker(io);
if (cluster.worker.id === 1) {
setInterval(() => {
io.emit('event', data); // works
io.of('/').emit('event', data); // works
io.of('somenamespace').emit('event', data); // works in half of the cases
}, 100);
}
io.on("connection", (socket) => {
/* ... */
});
}