【问题标题】:NodeJS Cluster with socket.io namespaces issue带有 socket.io 命名空间问题的 NodeJS 集群
【发布时间】:2021-09-23 17:09:03
【问题描述】:

我已经建立了一个带有 socket.io 的 NodeJS 集群,就像documentation 建议的那样。 在其中一名工人身上,我有发射器,它应该在一个循环中向所有客户端发射。在我开始使用命名空间之前一切正常。当发射到命名空间时,客户端(连接到命名空间)有时会收到事件,有时不会。似乎适配器没有在所有工作人员之间共享命名空间发射,并且客户端只有在连接到实际发射的工作人员时才会收到事件。任何人都可以建议如何制作所有客户端都将接收的命名空间发射吗?

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

【问题讨论】:

    标签: node.js sockets socket.io node-cluster


    【解决方案1】:

    在将正则表达式用于动态命名空间时,我遇到了一个间歇性问题。也许这就像你的问题。但是这个问题只发生在使用动态命名空间时。 My issue is here 我正在努力想出一个解决方法,但可能没有。

    【讨论】:

      猜你喜欢
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      • 2012-05-26
      • 2018-08-05
      • 2023-03-16
      相关资源
      最近更新 更多