首页 > 解决方案 > 使用 _rooms 向套接字所在的每个房间发射

问题描述

是否可以在没有 for 循环的情况下向一组房间(特别是套接字所在的所有房间)发射?类似于如何加入socket.join([roomArray])

标签: node.jssocket.io

解决方案


回答自己(在 Socket.IO Slack 的帮助下)。是的!

使用 for 循环

// You can rename the room variable whatever you want
for (const room of Object.keys(socket.rooms)) {
        socket.to(room).emit('news', { hello: 'world' });
}

没有 for 循环

您可以使用_rooms套接字的本机属性

// _rooms will be cleared once it has been emitted to
socket._rooms = Object.keys(socket.rooms);
// console.log(socket._rooms) = ['abc', 'efg', ...]
socket.emit('news', { hello: 'world' });
// console.log(socket._rooms) = []


推荐阅读