Tom*_*Tom 5 asp.net signalr signalr-hub
我是SignalR的新手,阅读API并玩弄它.对Hub及其Context有点困惑.
也就是说,Hub.Context不是HubContext.
HubContext 我可以得到 GlobalHost.ConnectionManager.GetHubContext<THub>()
并Hub.Context给我一个HubCallerContext我不知道如何使用.
他们的关系是什么?我怎么能得到HubContext from Hub或Hub from HubContext?
命名不佳的结果.Hub.Context是来自调用者的HTTP上下文(更像是请求上下文).在HubContext有GroupManager和Clients其映射到Hub.Groups和Hub.Clients.
您可以添加到组并从集线器外部与客户端通信.在集线器内部,您可以获取调用者的连接ID,并获取与集线器调用关联的HTTP请求上下文.在集线器之外,您不能这样做,Context.Clients.Caller或者Context.Clients.Others因为当您在集线器之外时没有呼叫者.
希望这能说明问题.
HubCallerContext是相对于当前请求的上下文.您将无法使用HubContext执行以下操作:
public class MyHub : Hub
{
public void Foo()
{
// These two are equivalent
Clients.Caller.bar();
Clients.Client(Context.ConnectionId).bar(); // Context.ConnectionId is the client that made the request connection id
}
}
Run Code Online (Sandbox Code Playgroud)
您无法使用HubContext执行此操作的原因是您没有Clients.Caller并且您没有Context.ConnectionId.
但是,您可以使用HubCallerContext对HubContext执行所有操作.
将HubCallerContext视为请求相对,更高级的HubContext版本.
当您想要将数据发送到请求上下文之外的集线器客户端时,最终会使用HubContext.
希望这可以帮助!