如何在节点js中使用ws(Websocket)包创建/加入聊天室

新手上路,请多包涵

我在服务器端使用 ws 包,我希望客户端在服务器套接字中创建/加入房间。并在它们不再连接时将它们从创建的房间中移除。 PS:我不想使用socketIo。

原文由 Mbula Mboma Jean gilbert 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 464
2 个回答

你可以尝试这样的事情:

 const rooms = {};

wss.on("connection", socket => {
  const uuid = ...; // create here a uuid for this connection

  const leave = room => {
    // not present: do nothing
    if(! rooms[room][uuid]) return;

    // if the one exiting is the last one, destroy the room
    if(Object.keys(rooms[room]).length === 1) delete rooms[room];
    // otherwise simply leave the room
    else delete rooms[room][uuid];
  };

  socket.on("message", data => {
    const { message, meta, room } = data;

    if(meta === "join") {
      if(! rooms[room]) rooms[room] = {}; // create the room
      if(! rooms[room][uuid]) rooms[room][uuid] = socket; // join the room
    }
    else if(meta === "leave") {
      leave(room);
    }
    else if(! meta) {
      // send the message to all in the room
      Object.entries(rooms[room]).forEach(([, sock]) => sock.send({ message }));
    }
  });

  socket.on("close", () => {
    // for each room, remove the closed socket
    Object.keys(rooms).forEach(room => leave(room));
  });
});

这只是一个草图:您需要处理离开房间、断开与客户端的连接(离开所有房间)以及当没有人在时删除房间。

原文由 Daniele Ricci 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用套接字或不使用套接字以这种方式创建用户和房间

const users = [];//It can be collection(noSQL) or table(SQL)

const addUser = ({ id, name, room }) => {
  name = name.trim().toLowerCase();
  room = room.trim().toLowerCase();

  const existingUser = users.find((user) => user.room === room && user.name === name);

  if(!name || !room) return { error: 'Username and room are required.' };
  if(existingUser) return { error: 'Username is taken.' };

  const user = { id, name, room };

  users.push(user);

  return { user };
}

原文由 Talha Noyon 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题