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

Emit 速查表

注意

以下事件名称是保留的,不能在您的应用程序中使用

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

服务器

单个客户端

基本 emit

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 秒内预期确认。

在服务器之间

基本 emit

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

客户端

基本 emit

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