Skip to main content
Version: 4.x

触发备忘单


danger

以下事件名称是保留的,不得在你的应用中使用:

英:The following event names are reserved and must not be used in your application:

  • 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");
tip

修饰符绝对可以链接起来:

英:The modifiers can absolutely be chained:

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

这将向所有连接的客户端发出 "hello" 事件:

英:This will emit a "hello" event to all connected clients:

  • 在名为 my-namespace 的命名空间中
  • 至少在名为 room1room2room3 的房间之一中,但不在 room4
  • 除发送者外

并期待在接下来的 5 秒内收到确认。

英:And expect an acknowledgement in the next 5 seconds.

服务器之间

基本触发

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

接收方:

英:Receiving side:

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)
}
});

接收方:

英:Receiving side:

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 {
// ...
}
});