问题
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