owl*_*owl 7 websocket node.js express 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?
});
});
Run Code Online (Sandbox Code Playgroud)
怎么做?
Son*_*hew 21
对于使用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");
}
Run Code Online (Sandbox Code Playgroud)
小智 2
请注意,此函数在高于 1.0 的 socket.io 版本中不再可用,建议保留 socket.id 的数组,以便在需要时可以迭代它们。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
});
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6592 次 |
| 最近记录: |