跳到主要內容
版本: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

若要在廣播時鎖定特定用戶端,請參閱有關 房間 的文件。