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

io.to not sending to specific client

我正在尝试向特定用户发送消息“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!");
            });

维护对每个客户端套接字的引用,该套接字由 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;
      };
    });
  });