The Magic of SignalR

I recently managed to find both the time and a suitable project to get my hands dirty with SignalR- a .NET library that provides real-time updates between web clients.

This post is a bit of a brain dump of the various things I worked through to get it doing what I wanted for the first time. Much of this will probably not apply to everyone - some may not even make sense - but hopefully someone will find it useful.

The Setup

As seems to be the case with most everything coming out for ASP.NET these days, SignalR is very quick to get up and running.

Before starting I had read a few tutorials and watched a couple of videos so I already had a pretty good idea that this would be the case, but it bears repeating: SignalR is ridiculously easy to set up. So much so that it almost feels like you’re cheating.

Once you’ve installed the nuget package you just create a Hub class and start adding methods.

Want to invoke server-side code from JavaScript? Easy - just add a method:

//server
public class ExampleHub : Hub
{
  public void SendMessage(string message)
  {
    //do something with message
  }
}

Then on the client just create and start a hub instance and call that method directly:

//client
$(function() {
  var hub = $.connection.exampleHub;

  $.connection.hub.start(function() {
    hub.sendMessage('a message from the client');
  });
});

How about calling the JavaScript clients from the server-side .NET code? Just call Clients.[method]:

//server
public void SendMessage(string message)
{
  Clients.receiveMessage(message);
}
//client
hub.receiveMessage = function(message) {
  alert('Received from server: ' + message);
};

That’s it! 5 minutes from “Install Package” to the basics of a chat client!

Filtering Bits Out

Having gotten to the “wow it works” stage pretty quickly, I started to write some real functionality and began to stumble across a few problems. Firstly, what if some clients don’t want to be notified of every message?

Take the class chat room example: if you have multiple rooms you really don’t want to send messages from room A to the people in rooms B, C and D. The way to solve this in SignalR is with Groups.

Filtering with Groups

Grouping with SignalR allows you to call methods on a subset of all clients based on a name:

public void SendMessage(string message)
{
  //only send message to group named 'Room A'
  Clients["Room A"].receiveMessage(message);
}

To get this to work you need to write a bit of code to assign clients to a group, which I implemented by adding a join method to my hub that the clients could call when they first connect:

//client
$(function() {
  $.connection.hub.start(function() {
    hub.join('Room A');
  });
});

On the server we need to associate the client that has called Join with the group name they have specified. SignalR already gives every client connection a unique identifier which is available through the Context.ConnectionId, and we use this ID to associate the current caller with the specified group.

//server
public void Join(string groupName)
{
  Groups.Add(Context.ConnectionId, groupName);
}

Once this is hooked up, only clients that explicitly join “Room A” will see the message for that room.

Filtering out the Caller

As well as avoiding sending messages to people who aren’t interested, I also wanted to avoid sending them back to the sender - after all, they already know about it.

Unfortunately there isn’t a similar solution to Groups (that I could find, anyway) so I had to take a different approach: send the message, but allow the client to filter it out.

I mentioned above that every client of a Hub is associated with a unique ConnectionId. If we pass this along with every message then each client can filter out anything that has originated from themselves:

hub.receiveMessage = function (message, from) {
  if (/* from !== this client */) {
    alert("Message from server: " + message);
  }
};

For some reason the hub implementation in JavaScript is not automatically aware of it’s connection ID, so to get this working client-side we need to add a little bit to our Join method to set that property on the client: Update: Damian Edwards mentions in the comments that you can get the connection ID without writing anything yourself using $.connection.hub.id, but I’m leaving in the below as it’s a nice example of setting properties on clients from the server.

//server
public void Join(string groupName)
{
  Caller.connectionId = Context.ConnectionId;
  //add to groups etc
}
//client
hub.receiveMessage = function(message, from) {
  if (from !== hub.connectionId) {
    alert('Message from server: ' + message);
  }
};

In the server code we are using the Caller property to refer to the client that has called Join. We can set a property on the caller and it just shows up on our hub object in JavaScript!

It’s not just about the messages

The primary function of SignalR is to allow real-time communication between server and client, but that’s not all that you can use the hubs for.

Lets suppose that when a client joins a room they are going to need to get some data - lists of participants, recent messages etc. We could write a Controller or WebAPI method to allow a client to get that information from the server, but why make a second call if we don’t need to? SignalR can handle all serialization of complex objects for us, so we can just return whatever information we want from the call to Join:

//server
public RoomInfo Join(string groupName)
{
  return new RoomInfo {
    Participants = { /*...*/ },
    RecentMessages = { /*...*/ }
  }
}

When a hub method returns an object, SignalR will automatically serialize it and return it as the first parameter to the done handler on the client:

//client
hub.join('Room A').done(function(roomInfo) {
  //use roomInfo object
});

The generated methods on the hub will in fact always return an instance of $.Deferred() to allow us to track the progress of a call.

To take things a step further you can use a hub almost as a replacement for WebAPI (as suggested by Yngve Bakken Nilsen here). Obviously this doesn’t make a sense in every scenario, but it is definitely an option, and I particularly like the fact that this method removes the need for URLs in the JavaScript.

A quick note on Windows Azure

For this particular project I was using Windows Azure preview to host the site, and on deploying it I noticed an extremely strange performance characteristic. The first notification that was sent from server to client was basically instantaneous, but all subsequent ones would take much much longer - up to 30s - to come through.

It took me a little while to get an answer, but eventually my Stack Overflow question was answered by David Fowler himself - there is a known issue with Windows Azure Preview sites that causes messages to be buffered.

The solution is very simple: just specify long polling as the desired transport mechanism:

$.connection.hub.start({ transport: 'longPolling' }, function() {
  //...
});

Once this is in place, every notification started coming through instantaneously.

The Conclusion

My first experience with SignalR was overwhelmingly positive. The effortless way it gives you live updates is immensely impressive, and when I did have problems I was able to find answers relatively quickly through Stack Overflow and other community sites.

The real beauty, though, is the fact that it is such a good abstraction from the underlying implementation that the first time you get it working it feels a little bit like magic.