socket.io v.4 如何在加入时获取房间内已有的插座列表

socket.io v.4 How to get list of sockets already in room when joining

我正在使用 socket.io (v4.0.1) 构建一个带有 React 和节点的聊天应用程序。我想获得已经加入房间的套接字(用户)列表,以便当用户加入房间时我可以向他们发送通知,让他们知道是否已经有其他人在线。有 a lot of examples 如何使用 socket.io 的早期版本执行此操作,但 none 似乎适用于版本 4。这是我的此事件的服务器代码:

  // join a room (chat) with the chat id
  socket.on('join chat', ({ chat, userId }) => {
    socket.join(chat.id);

    // this line is not working
    const clients = Object.keys(io.sockets.adapter.rooms[chat.id].sockets);
    // does not work
    // var roster = io.sockets.clients('chatroom1');


    const { users } = chat;

    if (!chat.users) return console.log('users not defined');

    // for each user in the conversation, send a notification to their own room
    // telling them someone joined the chat
    // want to let the user who joined (userId) know who is already there
    chat.users.forEach(user => {
      if (user._id === userId) return;
      socket.in(user._id).emit('user joined', userId);
    });

    console.log(`User with id ${userId} joined chat with id ${chat.id}`);
  });

Github 上得到了答案。希望这对某人有帮助:

// return all Socket instances
const sockets = await io.fetchSockets();
    
// return all Socket instances in the "room1" room of the main namespace
const sockets = await io.in("room1").fetchSockets();
    
// return all Socket instances in the "room1" room of the "admin" namespace
const sockets = await io.of("/admin").in("room1").fetchSockets();
    
// this also works with a single socket ID
const sockets = await io.in(theSocketId).fetchSockets();

文档:https://socket.io/docs/v4/server-instance/#Utility-methods