【问题标题】:How to update socket object for all clients in room? (socket.io)如何更新房间内所有客户端的套接字对象? (socket.io)
【发布时间】:2014-08-01 00:17:36
【问题描述】:
io.sockets.on('connection', function(socket) {
    socket.object = socket.id;

    socket.on('updateObject', function(data) {
        // How to update socket.object here for all clients?
    });
});

怎么做?

【问题讨论】:

标签: node.js express websocket socket.io


【解决方案1】:

对于使用 Socket.IO 1.0 或更高版本的用户,这是执行此操作的更新代码。

为房间中的所有客户端更新套接字对象的代码

var clients = io.sockets.adapter.rooms['Room Name'].sockets;   

//to get the number of clients
var numClients = (typeof clients !== 'undefined') ? Object.keys(clients).length : 0;

for (var clientId in clients ) {

     //this is the socket of each client in the room.
     var clientSocket = io.sockets.connected[clientId];

     //you can do whatever you need with this
     clientSocket.emit('new event', "Updates");

}

【讨论】:

  • API 又变了。要访问特定房间的客户端数组,请使用clients = io.sockets.adapter.rooms['Room Name'].sockets
  • 发射到您可以使用的单个房间:io.to('roomName').emit('event, 'msg');
  • 任何人都可以将API的文档指向socket.io/docs/server-api吗?我找不到。谢谢
  • 不知何故这对我也不起作用。它总是返回错误,Cannot read property 'rooms' of undefined 有什么帮助吗?
【解决方案2】:

请注意,此功能在高于 1.0 的 socket.io 版本中不再可用,建议保留一个 socket.id 的数组,以便您可以在需要时对其进行迭代。 example by ynos1234

您可以使用forEach 函数实现此目的:

io.sockets.on('connection', function(socket) {
socket.object = socket.id;

    socket.on('updateObject', function(data) {
        io.sockets.clients('room').forEach(function (socket, data) {
            // goes through all clients in room 'room' and lets you update their socket objects
        });
    });
});

【讨论】:

  • @ynos1234 更新了答案。
  • 我在下面为 Socket.IO 1.0 及更高版本添加了答案。
猜你喜欢
  • 2020-03-17
  • 2017-05-22
  • 2018-04-06
  • 1970-01-01
  • 1970-01-01
  • 2018-01-09
  • 2016-06-19
  • 2011-11-13
  • 2015-08-05
相关资源
最近更新 更多