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

问题描述 投票:0回答:1

我在单机上使用websockets/ws。它的工作正常。我想在多核和多个实例上水平扩展它。对于mutli-core,我尝试使用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')
});

和客户端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)
  }
});

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

   $ pm2 start ws-server.js -i 50
   $ pm2 start ws-client.js -i 50

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

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

node.js websocket pm2 node-cluster
1个回答
2
投票

不幸的是,在不同的进程中扩展Websocket很难,我建议你使用这个库:

https://github.com/ClusterWS/ClusterWS

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

© www.soinside.com 2019 - 2024. All rights reserved.