gpt4 book ai didi

node.js - socket.io v.4 如何在加入时获取房间内已有的套接字列表

转载 作者:行者123 更新时间:2023-12-05 09:05:35 25 4
gpt4 key购买 nike

我正在使用 socket.io (v4.0.1) 构建一个带有 React 和 Node 的聊天应用程序。我想获得已经加入房间的套接字(用户)列表,以便当用户加入房间时我可以向他们发送通知,让他们知道是否已经有其他人在线。有a lot of examples如何使用早期版本的 socket.io 执行此操作,但似乎都不适用于版本 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

关于node.js - socket.io v.4 如何在加入时获取房间内已有的套接字列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66966749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com