如何解决socket.io v.4 如何在加入时获取房间中已有的套接字列表
我正在使用 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
,我目前正在创建一个项目,其中一个电报机器人发出 gps 坐标,并且必须将它们发送到所有活动的套接字,我阅读了该页面的文档,但我不明白应该将代码放在何处这行 sockets = await io.fetchSockets(); 我留下了一个简单的代码示例:
const io = new Server(server);
bot.on('edited_message',(ctx) => {
console.log(ctx.editedMessage.location)
let sockets = await io.fetchSockets();
})
bot.launch()
io.on('connection',(socket) =>{
console.log('New connection ID: ' + socket.id);
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。