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

Mbu*_*ert 10 javascript node.js ws

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

Dan*_*cci 11

你可以尝试这样的事情:

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));
  });
});
Run Code Online (Sandbox Code Playgroud)

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


小智 5

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

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 };
}
Run Code Online (Sandbox Code Playgroud)

  • 你们的回答对我创建自己的答案有很大帮助。谢谢 (3认同)