在信号器中获取所有组名
本文关键字:获取 信号器 | 更新日期: 2023-09-27 18:35:07
好的,所以我有这段代码
var c = GlobalHost.ConnectionManager.GetHubContext<SomeHubClass>().Clients;
现在,客户端从这里返回一个具有 IHubConnectionContext 的 IHubConext,该上下文具有一个 IGroupManager 组。 现在无论如何都可以从中获取所有组名称吗?这是否可以通过 signalR 接口实现,或者我是否必须自己跟踪每个集线器的所有组?
SignalR 没有公开的 API,用于管理整个组、迭代组,甚至获取组的摘要列表。 您只能添加或删除组。 如果要保留组名称列表,也许可以为 SomeHubClass 使用单例模式。 在可以轻松访问的单例中保留List<string>
组名称,甚至保留一个Dictionary<string, HashSet<string>>
来映射连接 ID 的名称和哈希集,尽管在这种情况下这可能是矫枉过正的。
请参阅 http://www.asp.net/signalr/overview/hubs-api/hubs-api-guide-server#callfromoutsidehub,了解如何实现中心的单一实例。
您实际上可以使用反射获取所有组名(因为我们需要的所有字段都是私有的),就像我所做的那样,这也是我挖掘它的方式:IGroupManager -> _lifetimeManager -> _groups -> _groups
IGroupManager groupManager = signalRHubContext.Groups;
object lifetimeManager = groupManager.GetType().GetRuntimeFields()
.Single(fi => fi.Name == "_lifetimeManager")
.GetValue(groupManager);
object groupsObject = lifetimeManager.GetType().GetRuntimeFields()
.Single(fi => fi.Name == "_groups")
.GetValue(lifetimeManager);
IDictionary groupsDictionary = groupsObject.GetType().GetRuntimeFields()
.Single(fi => fi.Name == "_groups")
.GetValue(groupsObject) as IDictionary;
List<string> groupNames = groupsDictionary.Keys.Cast<string>().ToList();