【问题标题】:How webscokets connect to the correct child process inside a cluster?websockets如何连接到集群内正确的子进程?
【发布时间】:2019-09-20 00:23:30
【问题描述】:

我试图弄清楚 websockets 在 Nodejs/PM2 集群中是如何工作的。

我刚刚通过使用 PM2 启动 4 个子进程进行了一项实验,然后从客户端我向所有 4 个套接字服务器(每个子进程中运行 1 个 ws 服务器)发送了多个 webocket 消息。我没想到的一件事是 Node 能够确定套接字属于哪个进程,因此客户端发送的每条消息都由正确的子进程进行控制台记录。

那么这个行为是由 Nodejs 在内部由集群模块管理的吗?这似乎也是自 Node 12 以来的一个新功能?我可能错了……

代码参考(ws模块使用tsl):https://github.com/websockets/ws/blob/master/lib/websocket.js#L663

PS:在写答案之前,请检查我写给其他人的cmets...

【问题讨论】:

    标签: javascript node.js websocket pm2 ws


    【解决方案1】:

    你可以试试这个:

        webSocket=function(server) {
    
        var io = require('socket.io')(server,{ transports: ['websocket', 'polling'] });
        var redis = require('socket.io-redis');
        var pub = require('redis').createClient(6379,'localhost');
        var sub = require('redis').createClient(6379,'localhost');
        io.adapter(redis({pubClient: pub, subClient: sub}));
    
        io.sockets.on('connection', function (socket) {
            console.log('Connection Establish!!!!!');
        )}
    };
    
    
    app.JS
    https.createServer(options, app).listen(httpsAddress, function () {
        console.log("Express server listening on port " + config.get('PORT'));
        webSocket(this)
    })
    

    【讨论】:

      【解决方案2】:

      因此,基本上您需要一个集中式消息代理。 N 个进程将有 N 个非共享内存/配置/存储。最受欢迎的选择是redis。 Socket.io 通过redis-adapter 开箱即用地做到了这一点。

      所以, 1)安装redis 2)从here安装redis适配器

      之后你可以关注@pritamjana 的代码。

      来自适配器文档:

      通过使用 socket.io-redis 适配器运行 socket.io,您可以运行 不同进程或服务器中的多个 socket.io 实例 都可以相互广播和发射事件。

      const io = require('socket.io')(3000);
      const redisAdapter = require('socket.io-redis');
      io.adapter(redisAdapter({ host: 'localhost', port: 6379 }));
      
      // So any of the following commands:
      
      io.emit('hello', 'to all clients');
      io.to('room42').emit('hello', "to all clients in 'room42' room");
      
      io.on('connection', (socket) => {
        socket.broadcast.emit('hello', 'to all clients except sender');
        socket.to('room42').emit('hello', "to all clients in 'room42' room except sender");
      });
      

      【讨论】:

      • 为了让这段代码在集群中工作,服务器仍然需要跟踪每个 N 进程的连接。正如我的实验中所述,这正是发生的情况,我的问题是如何?还是谢谢你:)
      • 您发送给“所有 4 个套接字服务器”的问题是什么意思。那么为什么不控制台记录正确的呢?也许在你的问题中添加代码,这样我们就可以看到你想告诉什么。
      猜你喜欢
      • 2017-09-03
      • 2018-11-27
      • 2015-09-02
      • 2018-07-01
      • 2020-12-14
      • 1970-01-01
      • 2020-03-21
      • 2012-06-10
      相关资源
      最近更新 更多