使用多个服务器实例扩展 websockets/ws

Gag*_*gan 6 websocket node.js pm2 node-cluster

我在单机上使用websockets/ws 。它工作正常。我想在多核和多个实例上水平扩展它。对于多核,我尝试使用pm2,它似乎工作得很好。

第一个问题:这是最好的方法还是合适的方法?这是我使用 pm2 的测试代码

// ws-server.js
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 3131 });

var pid = process.pid + ''
console.log('process pid: '+ pid)

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    if (message === 'get-pid') {
      ws.send('pid-' + pid)
    } else {
      var matched = pid === message ? 'old friends' : 'strangers' 
      ws.send([pid, message, 'we are ' + matched].join(', '))
    }
  });
  ws.send('first time')
});
Run Code Online (Sandbox Code Playgroud)

和客户端 websocket 实例

// ws-cient.js
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:3131/');

var pid
ws.on('open', function open() {
  ws.send('get-pid');
  setInterval(function() {
    ws.send(pid)
  }, 1000)
});

ws.on('message', function incoming(data) {
  if (/^pid/.test(data)) {
    pid = data.match(/\d+/)[0]
    console.log('got pid: ' + pid) 
  } else {
    console.log(data)
  }
});
Run Code Online (Sandbox Code Playgroud)

只需使用 pm2 运行服务器和客户端

   $ pm2 start ws-server.js -i 50
   $ pm2 start ws-client.js -i 50
Run Code Online (Sandbox Code Playgroud)

如果您现在看到日志,pm2 logs ws-client每个客户端每秒都会点击相同的连接(在服务器上)。因此,对于多核 ws 可以与 PM2 配合使用。

第二个问题:如何扩展多个实例? 我刚刚看到SocketCluster用于水平扩展,但是它可以与 websockets/ws 一起使用吗,因为我已经使用 ws 开发了代码。水平缩放的其他解决方案可能是什么?

Dmi*_*nov 2

不幸的是,跨不同进程扩展 Websocket 会很困难,我建议您使用这个库:

https://github.com/ClusterWS/ClusterWS

该库的主要目的是跨进程和机器扩展 WebSocket。另外,好的一点是图书馆很小而且速度很快。

  • 该库现已存档/弃用 (6认同)