如何使用Node.js集群模块Express js添加粘性会话以使其与socket.io一起使用

时间:2019-06-11 13:02:44

标签: javascript node.js express websocket socket.io

我是Node.js的新手,请让我知道如何在该入门工具包(https://github.com/sahat/hackathon-starter)中添加Sticky Session,我想使express.js集群模块与socket.io一起工作。

当前,socket.io和express.js模块无法正常工作,我什至尝试将socket.io传输到websocket的传输更改为,但是socket.io仍然无法正常工作,客户端会将通知发送给Node .js服务器,但是socket.io发出的来自Node.js服务器的消息未到达客户端。

这是我关于集群模块的代码。

if (cluster.isMaster) {
    // Count the machine's CPUs
    var cpuCount = require('os').cpus().length;
    // Create a worker for each CPU
    for (var i = 0; i < cpuCount; i += 1) {
        cluster.fork();
    }
    // Listen for dying workers
    cluster.on('exit', function (worker) {
        // Replace the dead worker, we're not sentimental
        console.log('Worker %d died :(', worker.id);
        cluster.fork();
    });
// Code to run if we're in a worker process
} else {
    const app = express();
    var server = require('http').Server(app);
    const io = require('socket.io')(server);
    // My Socket.io code 
    // Socket io
    io.on("connection", socket => {

      socket.on("putOrder", order => {
        // i have tried both io.sockets.emit and io.emit to 
        io.sockets.emit("admin_order_placed",order);
        io.emit("admin_order_placed",order);
      });


    });
    /**
     * Start Express server.
     */
    server.listen(app.get('port'), () => {
        console.log('%s App is running at http://localhost:%d in %s mode', chalk.green('✓'), app.get('port'), app.get('env'));
      console.log('  Press CTRL-C to stop\n');
    });

}

编辑: 这是我的客户端Socket.io连接

import io from "socket.io-client";
var socket = io(this.state.endpoint,{ reconnection:true,reconnectionDelay : 1500,reconnect: true ,transports: ['websocket']});

有人可以让我知道如何在其中添加粘性会话,以便使我的socket.io正常工作吗?

0 个答案:

没有答案