UPDATE: With the release of SignalR 4.0, some of the information in the article may be out of date

I recently had to implement an ASP.NET MVC application using long polling to handle asynchronous communication not only from client from server (as you might traditionally do using ajax), but also server to client. I began looking into long polling solutions, and soon stumbled across SignalR, which describes itself as an async signaling library for ASP.NET to help build real-time, multi-user interactive web applications, which was pretty much exactly what I needed!

SignalR is a really brilliant solution. It’s one downfall, however, is the lack of documentation. Scott Hanselman wrote a nice post that gives a nice overview, with a code snippet that shows how easy it can be to use SignalR, but unfortunately there isn’t really much else (except for that one snippet, which seemed to appear everywhere!). Looking through the samples is also helpful, but some things I had to puzzle out on my own, and so I wanted to share some of what I learned. I’m not going to bother giving ‘real world’ type examples, simply show the different types of client/server communication SignalR is capable of, the building blocks. Once you know how to send data/call functions client to server, and vice versa, it really isn’t much of a leap to work out how to put it all together…

So there are two ways to use SignalR: you can access it at a low level by overriding it’s PersistentConnection class, which gives you a lot of control over it; or you can let SignalR do all of the heavy lifting for you, by using the high level ‘Hubs’.

SignalR Hubs

It’s so easy to set up a hub in your application. First, use Nuget to grab SignalR and it’s dependencies. In the root of your application, add a class, MyHub.cs that implements the SignalR class Hub. On your page, include jQuery and jquery.signalR, and then:

<script type="text/javascript" src="/signalr/hubs"></script><script type="text/javascript">// <![CDATA[
       $(function() {           var myConnection = $.connection.myHub;           $.connection.hub.start();       });
// ]]></script>

Rather awesomely, this is all you need to do to establish a connection between the client and server, which you can see if you crack open firebug. You’ll also notice that /signalr/hubs doesn’t actually exist in your project, which Resharper won’t like! This is really neat, as the hubs javascript is autogenerated by SignalR. Whilst we might have a connection established, it currently does nothing. Time to add some functionality.

Calling Server-side Functions from the Client

Everything with SignalR is basic, but this is probably the most basic of all. All you need to do is create the method in MyHub.cs, and then in your javascript simply call:

myConnection.voidFunction();

That really is it! If you build the solution and go to the source of /signalr/hubs, you’ll notice that it has been updated to include the new method. To pass some data, simply add values as you would in any other function:

myConnection.voidFunctionWithParams(1, "a string");

The methods don’t have to be void either. Say you have a function Increment:

public int Increment(int input) {
    return input++;
}

You call it simply by:

connection.returnInt(0)
          .done(function (returnedVal) {
              // Handle returned val (in this case, returnedVal = 1)
          });

As well as simple data types, you can also pass json to the server, and SignalR will automatically handle the conversion to objects. For example, if we have define a class MyObject:

public class MyObject {
    public int objId { get; set; }
    public string objVal { get; set; }
}

We can send it to the server like this:

var jsonMyObject = {
    "objId" : 1,
    "objVal" : "some text"
};
connection.receiveObject(jsonMyObject);

The reverse of this is true also, so returned objects from the server will be converted to their json equivalent.

Note: Static Variables

The hub class that you create will be instantiated at every request, so if you declare variables then they will be lost unless you make them static. This is useful for data that you want to persist, but not store in the database, as can be seen in the SignalR chat hub sample, which uses static collections to maintain the list of rooms.

Invoking client-side functions from the Server

So far I’ve only covered requests from client to server, which really is not a lot more useful than Ajax, albeit with some extra niceties such as object casting. The real usefulness of SignalR, however, comes with being able to call javascript functions from the server. I hope you won’t be surprised to learn, this is really easy to do! SignalR maintains a list of client side connections into the hub, rather conveniently named Clients. Client side functions must be defined in the initialisation code, for instance:

$(function() {
    var myConnection = $.connection.myHub;
    myConnection.alertMessage = function(stringParam) {
        alert(stringParam);
    };
    $.connection.hub.start();
});

This code simply creates an alert box that echoes the data passed to it, and is called by using

Clients.alertMessage("test");

Again, you can pass not only simple data types in here but C# objects and SignalR will handle the conversion. Taking this idea a little further we can pass in a list of MyObjects and iterate through them like this:

myConnection.receiveComplex = function(complexList) {
    complexList.each(function(index, complexObject) {
        var id = complexObject.objId;
        var value = complexObject.objVal;
    });
};

Invoking Client-side Functions from out of the Hub

Bouncing data back and forth between is cool, but the final useful thing you can do is to invoke javascript from outside the hub simply by:

var clients = Hub.GetClients();
clients.alertMessage("external test");

And there we have it! Asynchronous server/client messaging made easy!

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks

6 thoughts on “SignalR

  1. Hi Aaron, sorry I’m afraid I didn’t touch manually overriding the PersistentConnection. I believe, however, that the client side code to setup the connection will be the same, minus the signalr/hubs javascript call. You can then override any of the PersistentConnection methods which gives you total control (download SignalR and check the code, or have a look at Scott Hanselman’s blog post, to see the overridable methods). I’d guess the key method would be `protected virtual Task OnReceivedAsync(string clientId, string data)`. It doesn’t look like objects casting is done here, but you just send data through in whatever format you want, and deal with type conversions yourself if needsbe. Transmit data back using Connection.Broadcast(data). To be honest, this is all pretty much guesswork from Hanselman’s post, so you might want to study it a bit, and I can’t see how you might call client side functions from elsewhere like you can with hubs

    Reply
    • I have multiple roles in my project , i have to make connections to hubs across the project ..

      ex : In my project , Roles : Receptionist, Doctor

      When receptionist adds an appointment to particular doctor, then i have to notify and update the appointments list of a particular doctor in the page(where doctor is the role)

      Is it good to put entire server methods in one hub class , if not then how to make connection bt multiple hubs

      Can any one suggest how to handle this issue ?

      Reply
  2. Pingback: What do Hub represents in SignalR | FaceColony.com - Developers Network

Leave a reply

required

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>