小编典典

将响应发送给除发件人以外的所有客户端

javascript

要将内容发送给所有客户,请使用:

io.sockets.emit('response', data);

要从客户那里接收,您可以使用:

socket.on('cursor', function(data) {
  ...
});

如何将两者结合起来,以便在从客户端接收服务器上的消息时,将消息发送给所有用户,但发送消息的用户除外?

socket.on('cursor', function(data) {
  io.sockets.emit('response', data);
});

我是否必须通过发送带有消息的客户端ID,然后在客户端进行检查来破解它,还是有一种更简单的方法?


阅读 232

收藏
2020-04-25

共1个答案

小编典典

这是我的列表 (已更新为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) => {});
2020-04-25