广播事件
Socket.IO 使向所有连接的客户端发送事件变得容易。
信息
请注意,广播是仅服务器功能。
给所有连接的客户端


io.emit("hello", "world");
警告
当前断开连接(或正在重新连接)的客户端将不会收到该事件。将此事件存储在某处(例如在数据库中)取决于您的用例。
除发送者外的所有连接的客户端


io.on("connection", (socket) => {
socket.broadcast.emit("hello", "world");
});
备注
在上面的示例中,使用socket.emit("hello", "world")
(不带broadcast
标志)会将事件发送到“客户端 A”。您可以在备忘单中找到发送事件的所有方式的列表。
使用多个 Socket.IO 服务器
广播也适用于多个 Socket.IO 服务器。
您只需将默认适配器替换为Redis 适配器或其他兼容的适配器。


在某些情况下,您可能只想向连接到当前服务器的客户端广播。您可以使用local
标志实现此目的:
io.local.emit("hello", "world");


为了在广播时针对特定客户,请参阅有关Rooms的文档。