跳至主要内容
版本: 4.x

广播事件

Socket.IO 使得向所有连接的客户端发送事件变得容易。

信息

请注意,广播是**仅服务器**功能。

向所有连接的客户端

Broadcasting to all connected clientsBroadcasting to all connected clients
io.emit("hello", "world");
注意

当前断开连接(或正在重新连接)的客户端将不会收到该事件。根据您的用例,您需要将此事件存储在某个地方(例如数据库中)。

向所有连接的客户端(发送者除外)

Broadcasting to all connected clients excepting the senderBroadcasting to all connected clients excepting the sender
io.on("connection", (socket) => {
socket.broadcast.emit("hello", "world");
});
注意

在上面的示例中,使用socket.emit("hello", "world")(没有broadcast标志)将向“客户端 A”发送事件。您可以在速查表中找到所有发送事件的方法列表。

带确认

从 Socket.IO 4.5.0 开始,您现在可以将事件广播到多个客户端,并期望从每个客户端收到确认。

io.timeout(5000).emit("hello", "world", (err, responses) => {
if (err) {
// some clients did not acknowledge the event in the given delay
} else {
console.log(responses); // one response per client
}
});

所有广播形式都受支持

  • 在房间中
io.to("room123").timeout(5000).emit("hello", "world", (err, responses) => {
// ...
});
  • 从特定socket
socket.broadcast.timeout(5000).emit("hello", "world", (err, responses) => {
// ...
});
  • 在命名空间中
io.of("/the-namespace").timeout(5000).emit("hello", "world", (err, responses) => {
// ...
});

使用多个 Socket.IO 服务器

广播也适用于多个 Socket.IO 服务器。

您只需要用Redis 适配器或其他兼容适配器替换默认适配器。

Broadcasting with RedisBroadcasting with Redis

在某些情况下,您可能只想广播到连接到当前服务器的客户端。您可以使用local标志实现这一点。

io.local.emit("hello", "world");
Broadcasting with Redis but localBroadcasting with Redis but local

为了在广播时定位特定客户端,请参阅有关房间的文档。