SignalR - HubContext and Hub.Context

╄→гoц情女王★ 提交于 2019-12-10 15:11:26

问题


I am new to signalR and reading the API and playing around with it. a bit confused about the Hub and its Context.

That is, Hub.Context is not HubContext.

HubContext I can get from GlobalHost.ConnectionManager.GetHubContext<THub>()

and Hub.Context gives me a HubCallerContext which I am not sure how to use.

What are their relationship? How can I get HubContext from Hub or Hub from HubContext ?


回答1:


A result of poor naming. Hub.Context is the HTTP context from the caller (more like a request context). The HubContext has the GroupManager and Clients which map to Hub.Groups and Hub.Clients.

You can add to groups and talk to the client from outside the hub. Inside the hub you can get the connection ID of the caller and get the HTTP request context associated with the hub invocation. Outside of the hub, you can't do Context.Clients.Caller or Context.Clients.Others because there's no caller when you're outside of the hub.

Hope that clears things up.




回答2:


The HubCallerContext is a context that is relative to the current request. You would not be able to do the following using a 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
    }
}

The reason why you would not be able to do these with the HubContext is because you do not have a Clients.Caller and you do not have a Context.ConnectionId.

You can however do everything that you can do with a HubContext with a HubCallerContext.

Think of a HubCallerContext as a request relative, more advanced version of HubContext.

Ultimately HubContext is used when you want to send data to a hubs clients outside of the context of a request.

Hope this helps!



来源:https://stackoverflow.com/questions/19149949/signalr-hubcontext-and-hub-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!