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

發送備忘清單

注意

下列事件名稱是保留的,不得在您的應用程式中使用

  • connect
  • connect_error
  • disconnect
  • disconnecting
  • newListener
  • removeListener
// BAD, will throw an error
socket.emit("disconnecting");

伺服器

單一用戶端

基本發送

io.on("connection", (socket) => {
socket.emit("hello", 1, "2", { 3: "4", 5: Buffer.from([6]) });
});

確認

io.on("connection", (socket) => {
socket.emit("hello", "world", (arg1, arg2, arg3) => {
// ...
});
});

確認和逾時

io.on("connection", (socket) => {
socket.timeout(5000).emit("hello", "world", (err, arg1, arg2, arg3) => {
if (err) {
// the client did not acknowledge the event in the given delay
} else {
// ...
}
});
});

廣播

至所有已連線的用戶端

io.emit("hello");

除了傳送者

io.on("connection", (socket) => {
socket.broadcast.emit("hello");
});

確認

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("my room").emit("hello");
  • 至所有已連線用戶端,除了名為「我的房間」房間中的用戶端
io.except("my room").emit("hello");
  • 具有多個子句
io.to("room1").to(["room2", "room3"]).except("room4").emit("hello");

在一個命名空間中

io.of("/my-namespace").emit("hello");
提示

這些修飾詞絕對可以串連使用

io.of("/my-namespace").on("connection", (socket) => {
socket
.timeout(5000)
.to("room1")
.to(["room2", "room3"])
.except("room4")
.emit("hello", (err, responses) => {
// ...
});
});

這會向所有已連線的用戶端發出「hello」事件

  • 在名為my-namespace的命名空間中
  • 在名為room1room2room3的房間中至少一個,但不在room4
  • 除了傳送者

並在接下來的 5 秒內期待確認。

伺服器之間

基本發送

io.serverSideEmit("hello", "world");

接收端

io.on("hello", (value) => {
console.log(value); // "world"
});

確認

io.serverSideEmit("hello", "world", (err, responses) => {
if (err) {
// some servers did not acknowledge the event in the given delay
} else {
console.log(responses); // one response per server (except the current one)
}
});

接收端

io.on("hello", (value, callback) => {
console.log(value); // "world"
callback("hi");
});

用戶端

基本發送

socket.emit("hello", 1, "2", { 3: "4", 5: Uint8Array.from([6]) });

致謝

socket.emit("hello", "world", (arg1, arg2, arg3) => {
// ...
});

致謝和逾時

socket.timeout(5000).emit("hello", "world", (err, arg1, arg2, arg3) => {
if (err) {
// the server did not acknowledge the event in the given delay
} else {
// ...
}
});