xb18
xb18
文章39
标签0
分类0
socket.io使用

socket.io使用

room

加入房间

1
2
3
io.on("connection", (socket) => {
socket.join("some room");
});

广播

1
2
3
4
5
6
io.to("room1").to("room2").to("room3").emit("some event"); // 或使用io.in('room1')
// 从给定的socket广播到房间 在这种情况下,房间中除发送者之外的每个socket都会收到该事件
io.on("connection", (socket) => {
// socket.to("some room").emit("some event"); // To all connected clients
socket.broadcast.to("some room").emit("some event"); // Except the sender
});

默认房间

Socket.IO 中的每一个socket都由一个随机的、不可猜测的、唯一的标识符Socket#id。为了您的方便,每个socket都会自动加入一个由其自己的 id 标识的房间。

这使得实现私人消息变得容易:

1
2
3
4
5
io.on("connection", (socket) => {
socket.on("private message", (anotherSocketId, msg) => {
socket.to(anotherSocketId).emit("private message", socket.id, msg);
});
});
本文作者:xb18
本文链接:http://xb18.github.io/2023/10/12/socketio/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可