socket.io消息仍然在广播,即使客户已经离开了房间

socket.io message still broadcasted even though client has left the room

本文关键字:客户 离开 房间 消息 io 广播 socket      更新时间:2023-09-26

我制作了一个聊天应用程序,人们可以在其中加入/离开房间。我遇到了一些非常奇怪的事情,我真的无法理解

这是我的server.js(后端)的摘录:

client.on("send", function(msg) {
  console.log("Sending to ==> " + client.room);
  if ('undefined' !== typeof client.room) {
    socket.sockets.in(client.room).emit("chat", people[client.id], msg);
  }
});

我本质上是在"强迫"人们加入一个房间(如果他们不在房间里,client.room返回undefined。)

我在前端放了两个按钮,一个用于加入房间,另一个用于离开房间。加入按钮通过以下方式处理:

client.on("joinRoom", function(name) {
  client.join(name); //where name is the name of the room coming from the frontend
 }

离开房间的功能如下:

client.on("leaveRoom", function(name) {
  client.leave(name);
}

现在,问题是:客户离开后(姓名);位,用户仍然可以发送消息和console.log("Sending to===>"+client.room);仍将输出"发送到===>room1"),而客户端已离开房间。我用"socket.sockets.clients(client.room)"确认了这一点——这里不再列出客户端。

有人知道为什么我仍然从客户那里向他不在的房间发送消息吗?

更新

在收到DRC的回复后,我更新了我的发送功能:

client.on("send", function(msg) {
  for (key in socket.sockets.manager.roomClients[client.id]) {
    if (key ==="/" + client.room) {
      socket.sockets.in(client.room).emit("chat", people[client.id], msg);  
    }
  }
});

这是最优雅的解决方案吗?

您正在分配client.room,而不是在客户端离开房间时将其删除,socket.io没有为此检查授权,您必须这样做。

因此,每当客户端离开房间时,都要删除client.room,或者检查用户是否在房间中检查io.sockets.manager.roomClients[socket.id]的内容,请参阅文档

更新 术后问题模块

你已经有了房间名称,所以房间客户端的密钥[socket.id],你可以检查:

if (socket.sockets.manager.roomClients[client.id]['/'+client.room] !== undefined ){
    //the user is part of this room
}

但是的,这就是逻辑。