io.to 不发送到特定客户端

时间:2021-04-30 07:18:07

标签: javascript socket.io

我正在尝试向特定用户发送消息“newAllowedUserAlert”。然而,问题是它根本没有发送给用户。为了调试,我检查了 userToAllow 是否已正确定义,并且确实如此。我怀疑问题是我正在设置 customId,但我确保没有用户来两次,因此没有重复的 ID。我认为 customId 是错误还是其他原因是正确的吗?

服务器端:

io.on("connection", function (socket) {
    socket.on("newUser", async function (userData) {
      const {isUserHost, customId} = userData;

      // Maybe only use original ID instead of customId?
      socket.id = customId;

      const [room, email] = customId.split(" ");
      const roomCriteria = {uuid: room};

      await Call.updateOne(roomCriteria, {
        $push: {
          currentUserEmails: email
        }
      });
      
      socket.join(room);

      if (isUserHost) {
        socket.on("newAllowedUserId", async function (userToAllow) {
          const emailToAllow = userToAllow.split(" ")[1];

          await Call.updateOne(roomCriteria, {
            $push: {
              allowedUserEmails: emailToAllow
            }
          });

          io.to(userToAllow).emit("userIsAllowedAlert", "");
        });
      };
    });
  });

客户端:

socket.on("userIsAllowedAlert", function () {
              alert("You are allowed!");
            });

1 个答案:

答案 0 :(得分:0)

维护对每个客户端套接字的引用,该引用由 customId 索引并在需要时发送给它们。

const myClientList = {};

  io.on("connection", function (socket) {
    socket.on("newUser", async function (userData) {
      const {isUserHost, customId} = userData;

      // Maybe only use original ID instead of customId?
      socket.id = customId;

      const [room, email] = customId.split(" ");
      const roomCriteria = {uuid: room};

      await Call.updateOne(roomCriteria, {
        $push: {
          currentUserEmails: email
        }
      });
      
      socket.join(room);

      if (isUserHost) {
        socket.on("newAllowedUserId", async function (userToAllow) {
          const emailToAllow = userToAllow.split(" ")[1];

          await Call.updateOne(roomCriteria, {
            $push: {
              allowedUserEmails: emailToAllow
            }
          });

          const userToAllowSocket = myClientList[userToAllow];

          if (userToAllowSocket) {
            userToAllowSocket.emit("userIsAllowedAlert", "");
          };
        });
      } else {
        myClientList[customId] = socket;
      };
    });
  });