【问题标题】:How to find all sockets in room using the latest version of Socket.io如何使用最新版本的 Socket.io 查找房间中的所有套接字
【发布时间】:2020-06-04 23:41:50
【问题描述】:

因此,使用 socket.io version 您可以使用:

var clients = io.sockets.clients('room');

获取房间“房间”中的所有插座。

但是现在使用最新版本的 socket.io 这是不可能的,我还没有找到适用于最新版本的解决方案,我不希望降级版本来运行我的应用程序。

【问题讨论】:

    标签: javascript node.js socket.io


    【解决方案1】:
            var clients= io.sockets.adapter.rooms[room].sockets
    

    似乎成功了!

    【讨论】:

      【解决方案2】:

      您可以使用 Socket Redis Adapter 来管理 SocketIO 房间。

      const io = require('socket.io')(3000);
      const redisAdapter = require('socket.io-redis');
      io.adapter(redisAdapter({ host: 'localhost', port: 6379 }));
      
      io.on('connection', function(client) {
          //Get allRooms by Redis Adapter
          io.of('/').adapter.allRooms((err, rooms) => {
              for (let room of rooms) {
                   //Handle your room
              }
          })
      })
      

      希望对您有所帮助!

      【讨论】:

      • 如果您已经在使用 Redis pubsub,这可能是一个很好的解决方案,但是将 Redis 数据库添加到项目中只是为了获取房间中的客户列表并不是一个好主意。跨度>
      【解决方案3】:

      根据socket.io 2.0 docs

      io.in('room').clients((error, clients) => {
        if (error) throw error;
        console.log(clients); // => [Anw2LatarvGVVXEIAAAD]
      });
      

      并获取客户端 ID 的套接字:

      io.sockets.sockets[client]
      

      (是的,2 次套接字)

      【讨论】:

        猜你喜欢
        • 2014-08-01
        • 2020-03-17
        • 2013-10-03
        • 2018-12-11
        • 2012-06-09
        • 1970-01-01
        • 1970-01-01
        • 2017-03-21
        • 1970-01-01
        相关资源
        最近更新 更多