运行socketio和nodejs集群模块

时间:2019-02-21 00:28:29

标签: node.js reactjs express socket.io

服务器

var cluster = require('cluster');

// Code to run if we're in the master process
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 terminating workers
    cluster.on('exit', function (worker) {

        // Replace the terminated workers
        console.log('Worker ' + worker.id + ' died :(');
        cluster.fork();

    });

// Code to run if we're in a worker process
}

else {
    const app = express();
    const server = require('http').createServer(app);

    const io = require('socket.io')(server);
    app.set('socketio', io);

    const port = process.env.PORT || 9090;

    server.listen(port,() => {
        console.log('Server running at http://127.0.0.1:' + port + '/');
    });
    io.on('connection', function (socket) {
      console.log("CONNECTED")
    });


}

客户

import io from 'socket.io-client'
    const socket = io('http://localhost:9090');
    socket.on('notification', (data) => {
      if(props.user && data.user._id === props.user._id) {
        this.setNotification(data.notification);
      }
    })

错误消息  http://localhost:9090/socket.io/?EIO=3&transport=polling&t=MaDRz1u&sid=VzBUqt22usNbdqKCAAAb 400(错误请求)

当我删除if else并保留else语句中的代码时,一切正常。我需要添加什么,以便sessionID未知。

响应对象为{“代码”:1,“消息”:“会话ID未知”}

1 个答案:

答案 0 :(得分:1)

之所以发生这种情况,是因为群集创建的每个子进程都不同步,彼此之间也不认识。为了克服这个问题,您将需要一个适配器在群集之间进行通信。

Refer the Socket.io documentation以解决此问题。