-
Notifications
You must be signed in to change notification settings - Fork 0
Hubs
Hubs provide a higher level MVC style framework over a PersistentConnection. If you have different types of messages that you want to send between server and client then hubs is recommended so you don't have to do your own dispatching.
To get started using Hubs, create a class that derives from Hub.
public class MyHub : Hub
{
}
Unlike low level PersistentConnections, there's no need to specify a route for the hub as they are automatically accessible over a special url (/signalr/hubs).
To expose methods on the hub that you want to be callable from the client. Simply declare a public method:
public class MyHub : Hub
{
public string Send(string data)
{
return data;
}
}
This makes the Send method callable from any SignalR client.
To call client event/methods from the server use the Clients property.
public class MyHub : Hub
{
public void Send(string data)
{
Clients.addMessage(data);
}
}
The above code will invoke the addMessage method on the client with specified data.
Invoking methods on the the Clients property on hub will broadcast that message to all connected clients. But there are some cases where we want to send a specific clients or groups. We can use the indexer on the Clients object to specify a group name or a client id. You can also use the Caller property on the Hub to invoke methods on the calling client on the hub.
public class MyHub : Hub
{
public void Send(string data)
{
// Invoke a method on the calling client
Caller.addMessage(data);
// Similar to above, the more verbose way
Clients[Context.ClientId].addMessage(data);
// Invoke addMessage on all clients in group foo
Clients["foo"].addMessage(data);
}
}
Under the covers the Clients/Caller property is a dynamic object that wraps an IConnection. Method calls on that object call Broadcast with method invocation data that the clients interprets.
- Anything you return from the hub will be serialized into JSON and sent to the client.
- You may also return Task/Task from a hub if you need to do async work.
- Any state sent from the client can be accessed via the Caller property.
- You can also set client side state just by setting any property on Caller.
Example
public class MyHub : Hub
{
public void Send(string data)
{
// Access the id property set from the client.
string id = Caller.id;
// Set a property on the client state
Caller.name = "SignalR";
}
}
NOTE: Hubs are per call, that is, each call from the client to the hub will create a new hub instance. So don't setup static event handlers in hub methods.