在节点中扩展websocket

时间:2018-08-02 08:43:42

标签: node.js websocket

如何使用pm2在集群模式下在多个服务器上然后在多个处理器上扩展websocket? Websocket仅在一个群集上工作。套接字的群集已由我实现,但是在使用websocket时失败。

1 个答案:

答案 0 :(得分:0)

我已经在一台服务器上运行集群中的websocket应用,该服务器仅使用Node.Js内置集群模块,具有四个内核的CPU。

此应用是使用websocket的简单聊天服务器,代码如下:

// Dependencies
const cluster = require('cluster');
const os = require('os');
const WS = require('ws').Server;


// Instantiate the server module object
const server = {};


 // Init script
server.init = function(){
    // Start the websocket server
    server.s = new WS({port: 555});

    console.log('The websocket server is running on port 555');

    // main websocket-server event
    server.s.on('connection', function(ws){

        console.log("One more client connected");

        ws.on('close', function(){
            console.log("One client disconnected");
        });

        // main onmessage event
        ws.on('message', function(message){
            // log on server side console
            console.log('Received: ' + message);

            // message here is json object Not simple string
            msg = JSON.parse(message)

            // save client name on its ws object
            if(msg.type == 'name'){
                ws.personeName = msg.data;
                return;
            }

            // broadcast my message to other clients        
            server.s.clients.forEach(function e(client){
                if(client != ws)
                    client.send(JSON.stringify({
                        name: ws.personeName,
                        data: msg.data
                    }));
            }); 
        }); 

    });

};


// Self invoking only if required directly
if(require.main === module){

  if(cluster.isMaster){

    // Fork the process
    for(let i = 0; i < os.cpus().length; i++){
      cluster.fork();
    }

  } else {
    // If we're not on the master thread, start the websocket server
    server.init();
  }

};

运行该应用程序后,我从四个线程(每个CPU核心一个线程)中收到了四个日志消息:

The websocket server is running on port 555
The websocket server is running on port 555
The websocket server is running on port 555
The websocket server is running on port 555