如何更新房间内所有客户端的套接字对象? (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? }); }); 

怎么做?

请注意,这个函数在socket.io版本高于1.0的时候是不可用的,build议保留一个你的socket.id的数组,以便在需要的时候迭代它们。 例如通过ynos1234

你可以用forEach函数来实现这个function:

 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 }); }); }); 

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