如何更新房间内所有客户端的套接字对象? (socket.io)

时间:2014-06-11 04:07:44

标签: node.js express websocket socket.io

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

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

怎么做?

2 个答案:

答案 0 :(得分:20)

对于使用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");

}

答案 1 :(得分: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
        });
    });
});