node.js - 使用 _rooms 向套接字所在的每个房间发射
问题描述
是否可以在没有 for 循环的情况下向一组房间(特别是套接字所在的所有房间)发射?类似于如何加入socket.join([roomArray])
?
解决方案
回答自己(在 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) = []
推荐阅读
- javascript - 为什么在使用 redux 时,这两种情况下的 react 渲染会不同?
- php - 显示已选中复选框的选中图标(刻度)。| 拉拉维尔 | (复选框,如在 WordPress 中)
- python - Azure 功能无法纵向扩展
- javascript - 映射时从数组中删除重复项
- powershell - 将列添加到 Powershell 显示输出
- angular - 当我有来自拦截器的不同标头时,角度标头不会添加到特定请求中
- python-3.x - 在 Ubuntu 20.04 LTS 上使用 Python 3.x 在 VS Code 中无法解析 Pylance (reportMissingImports) 导入“Path.to.own.script”
- excel - 从一张纸复制数据并在另一张纸上替换
- r - 根据值的现有信息更改列的值?
- tensorflow - 训练期间测试数据的输出精度