Skip to content
davidfowl edited this page Nov 5, 2011 · 49 revisions

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).

Client Calling the server

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.

Server calling the 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.

Calling methods on specific clients or groups

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.

public class MyHub : Hub
{
     public void Send(string data)
     {
         Clients[Context.ClientId].addMessage(data);
         Clients["foo"].addMessage(data);
     }
}

How it works

Under the covers the Clients property is a dynamic object that wraps an IConnection. Method calls on that object call Broadcast with method invocation data that the clients interprets.

Clone this wiki locally