向除发送者外的所有客户端发送响应

274

要将某物发送给所有客户端,您可以使用:

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

要从客户端接收数据,你需要使用:

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

我该怎么样合并这两个功能,使得当服务器从客户端接收到一条消息时,将该消息发送给除发送方以外的所有用户?

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

我是否需要通过在消息中发送客户端ID并在客户端上进行检查来解决问题,还是有更简单的方法?

12个回答

971

这是我的列表(更新至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) => {});

15
您希望将这个内容贡献给 常见问题解答 吗?还是让我来为您做这件事?(我可以在此提供后向链接) - Kos
1
我这里没有 io,只有 socket - chovy
2
除了“// 发送给除发送者之外的所有客户端”之外,用什么来“// 仅向发送方客户端发送响应”? - Basj
4
根据socket#in,请添加以下内容:socket.to('others').emit('an event', { some: 'data' });也可以在房间内进行广播 - gongzhitaao
144
这比socket.io文档中的所有内容都更有用。 - Jonathan.
显示剩余16条评论

46

参考 @LearnRPG 回答,但使用 1.0 版本:

 // send to current request socket client
 socket.emit('message', "this is a test");

 // sending to all clients, include sender
 io.sockets.emit('message', "this is a test"); //still works
 //or
 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
 // docs says "simply use to or in when broadcasting or emitting"
 io.in('game').emit('message', 'cool game');

 // sending to individual socketid, socketid is like a room
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');

为了回答 @Crashalot 评论中的问题,“socketid”来自于以下代码:
var io = require('socket.io')(server);
io.on('connection', function(socket) { console.log(socket.id); })

3
太棒了!如何获取 socketid 并将消息发送到特定的 socket? - Crashalot
2
编辑后附上了你的问题答案。基本上它是从你的socket对象中获取的socket.id - soyuka
对于要发送到个人的内容,您可以使用socket.emit返回发送者,或者您可以将连接的客户端分组并执行@Crashalot。 - ujwal dhakal

13

以下是从0.9.x到1.x发生的更完整的变化。

 // send to current request socket client
 socket.emit('message', "this is a test");// Hasn't changed

 // sending to all clients, include sender
 io.sockets.emit('message', "this is a test"); // Old way, still compatible
 io.emit('message', 'this is a test');// New way, works only in 1.x

 // sending to all clients except sender
 socket.broadcast.emit('message', "this is a test");// Hasn't changed

 // sending to all clients in 'game' room(channel) except sender
 socket.broadcast.to('game').emit('message', 'nice game');// Hasn't changed

 // sending to all clients in 'game' room(channel), include sender
 io.sockets.in('game').emit('message', 'cool game');// Old way, DOES NOT WORK ANYMORE
 io.in('game').emit('message', 'cool game');// New way
 io.to('game').emit('message', 'cool game');// New way, "in" or "to" are the exact same: "And then simply use to or in (they are the same) when broadcasting or emitting:" from http://socket.io/docs/rooms-and-namespaces/

 // sending to individual socketid, socketid is like a room
 io.sockets.socket(socketid).emit('message', 'for your eyes only');// Old way, DOES NOT WORK ANYMORE
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');// New way

我想编辑@soyuka的帖子,但我的编辑被同行审查拒绝了。

8

Emit速查表

io.on('connect', onConnect);

function onConnect(socket){

  // sending to the client
  socket.emit('hello', 'can you hear me?', 1, 2, 'abc');

  // sending to all clients except sender
  socket.broadcast.emit('broadcast', 'hello friends!');

  // sending to all clients in 'game' room except sender
  socket.to('game').emit('nice game', "let's play a game");

  // sending to all clients in 'game1' and/or in 'game2' room, except sender
  socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");

  // sending to all clients in 'game' room, including sender
  io.in('game').emit('big-announcement', 'the game will start soon');

  // sending to all clients in namespace 'myNamespace', including sender
  io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');

  // sending to individual socketid (private message)
  socket.to(<socketid>).emit('hey', 'I just met you');

  // sending with acknowledgement
  socket.emit('question', 'do you think so?', function (answer) {});

  // sending without compression
  socket.compress(false).emit('uncompressed', "that's rough");

  // sending a message that might be dropped if the client is not ready to receive messages
  socket.volatile.emit('maybe', 'do you really need it?');

  // sending to all clients on this node (when using multiple nodes)
  io.local.emit('hi', 'my lovely babies');

};

7

broadcast.emit会将消息发送给所有其他客户端(除了发送者)

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

4

对于在房间内的命名空间,循环遍历房间中的客户端列表(类似于 Nav 的答案)是我发现的仅有的两种方法之一。另一个方法是使用排除。例如:

socket.on('message',function(data) {
    io.of( 'namespace' ).in( data.roomID ).except( socket.id ).emit('message',data);
}

7
"except" 已从 1.x 版本中移除 :/ (说明:该句为技术文档或代码注释,意为某个功能或语法在新版本中已经被删除) - coulix

3

V4.x中有效的服务器端所有emit事件列表

io.on("connection", (socket) => {

// basic emit
socket.emit(/* ... */);

// to all clients in the current namespace except the sender
socket.broadcast.emit(/* ... */);

// to all clients in room1 except the sender
socket.to("room1").emit(/* ... */);

// to all clients in room1 and/or room2 except the sender
socket.to(["room1", "room2"]).emit(/* ... */);

// to all clients in room1
io.in("room1").emit(/* ... */);

// to all clients in room1 and/or room2 except those in room3
io.to(["room1", "room2"]).except("room3").emit(/* ... */);

// to all clients in namespace "myNamespace"
io.of("myNamespace").emit(/* ... */);

// to all clients in room1 in namespace "myNamespace"
io.of("myNamespace").to("room1").emit(/* ... */);

// to individual socketid (private message)
io.to(socketId).emit(/* ... */);

// to all clients on this node (when using multiple nodes)
io.local.emit(/* ... */);

// to all connected clients
io.emit(/* ... */);

// WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
// named `socket.id` but the sender. Please use the classic `socket.emit()` instead.

// with acknowledgement
socket.emit("question", (answer) => {
    // ...
});

// without compression
socket.compress(false).emit(/* ... */);

// a message that might be dropped if the low-level transport is not writable
socket.volatile.emit(/* ... */);

});

客户端

// basic emit
    socket.emit(/* ... */);

// with acknowledgement
    socket.emit("question", (answer) => {
        // ...
    });

// without compression
    socket.compress(false).emit(/* ... */);

// a message that might be dropped if the low-level transport is not writable
    socket.volatile.emit(/* ... */);

存档源链接 => http://archive.today/2021.06.22-023900/https://socket.io/docs/v4/emit-cheatsheet/index.html


此链接为 Socket.IO 官方文档的 emit-cheatsheet 页面存档链接。

1
其他情况
io.of('/chat').on('connection', function (socket) {
    //sending to all clients in 'room' and you
    io.of('/chat').in('room').emit('message', "data");
};

1

更新了列表以供进一步文档使用。

socket.emit('message', "this is a test"); //sending to sender-client only
socket.broadcast.emit('message', "this is a test"); //sending to all clients except sender
socket.broadcast.to('game').emit('message', 'nice game'); //sending to all clients in 'game' room(channel) except sender
socket.to('game').emit('message', 'enjoy the game'); //sending to sender client, only if they are in 'game' room(channel)
socket.broadcast.to(socketid).emit('message', 'for your eyes only'); //sending to individual socketid
io.emit('message', "this is a test"); //sending to all clients, include sender
io.in('game').emit('message', 'cool game'); //sending to all clients in 'game' room(channel), include sender
io.of('myNamespace').emit('message', 'gg'); //sending to all clients in namespace 'myNamespace', include sender
socket.emit(); //send to all connected clients
socket.broadcast.emit(); //send to all connected clients except the one that sent the message
socket.on(); //event listener, can be called on client to execute on server
io.sockets.socket(); //for emiting to specific clients
io.sockets.emit(); //send to all connected clients (same as socket.emit)
io.sockets.on() ; //initial connection from a client.

希望这有所帮助。

'io.sockets.emit' 和 'io.emit' 是相同的,不是 'socket.emit'。 - Doctor.Who.
"socket.to('game').emit" 等同于 "socket.broadcast.to('game').emit",因此上面的注释是错误的。 - Doctor.Who.

1

已更新至 Socket.io v4.0.0+

在v4中向除发送者外的所有客户端发出消息,您可以使用以下代码:

socket.broadcast.emit(/* ... */);

示例用法
io.on("connection", (socket) => {
   socket.on("message", (message) => {
      //sends "newMessage" to all sockets except sender
      socket.broadcast.emit("newMessage", message)
   })
})

如何在一次调用中包含发送者? - MartianMartian
io.sockets.emit - Coder Gautam YT
抱歉,我的意思是如果io.sockets不可用。 - MartianMartian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接