要将某些内容发送给所有客户端,请使用:
io.sockets.emit('response', data);
要从客户那里接收,您使用:
socket.on('cursor', function(data) { ... });
如何将两者结合起来,以便在服务器上从客户端接收消息时,将该消息发送给除发送消息的用户之外的所有用户?
socket.on('cursor', function(data) { io.sockets.emit('response', data); });
我是否必须通过发送带有消息的客户端 ID 然后检查客户端来破解它,还是有更简单的方法?
这是我的清单 (针对 1.0 更新) :
// sending to sender-client only socket.emit('message', "this is a test"); // sending to all clients, include sender io.emit('message', "this is a test"); // sending to all clients except sender socket.broadcast.emit('message', "this is a test"); // sending to all clients in 'game' room(channel) except sender socket.broadcast.to('game').emit('message', 'nice game'); // sending to all clients in 'game' room(channel), include sender io.in('game').emit('message', 'cool game'); // sending to sender client, only if they are in 'game' room(channel) socket.to('game').emit('message', 'enjoy the game'); // sending to all clients in namespace 'myNamespace', include sender io.of('myNamespace').emit('message', 'gg'); // sending to individual socketid socket.broadcast.to(socketid).emit('message', 'for your eyes only'); // list socketid for (var socketid in io.sockets.sockets) {} OR Object.keys(io.sockets.sockets).forEach((socketid) => {});