0

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) => {
        /* ... */
    });
} 

1 Answer 1

0

I have faced an intermittent issue when using a regex expression for dynamic namespace. Maybe be it's like your issue. But this issue only occurs when using dynamic namespace. My issue is here I'm trying hard to come up with a workaround, but there just might not be one.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.