.NET Technical Guide: SignalR

SignalR is a library for ASP.NET and JavaScript that enables real-time communication between server and one or more clients, allowing web applications to behave more like desktop applications. While relatively new, SignalR is rapidly gaining adoption due to its ease of use and cross-browser compatibility.

Microsoft recognizes the game-changing nature of SignalR and has thrown its full weight behind the technology by including it as a class template in Visual Studio 2013. If you are still using 2012, a couple additional steps will be required before you can get started.

When possible, SignalR utilizes HTML5 WebSockets to maintain a bidirectional channel of communication; at a minimum, this feature requires the server to be using .NET Framework 4.5 on either Windows 8 or Server 2012. If WebSockets are unsupported by either client or server, SignalR intelligently falls back on more traditional technologies, such as Server-Sent Events (FF6+, Chrome, Opera 11+, Safari 5+,) Forever Frame (IE9+,) and ajax long polling as a last resort.

Although this guide focuses on SignalR as a web technology, the library is not limited to JavaScript clients. Stand-alone desktop, Windows Phone, Silverlight, Java (including Android) and iOS client packages are also available.

Use Cases

SignalR proffers an exciting new paradigm for web development, but the temptation to use it throughout your application must be resisted. SignalR is not intended to replace traditional WCF or Web API, but rather to augment them.

SignalR is a great candidate for implementing a variety of “live” features, including chat, status alerts, dashboard updates, and progress bars. However, in cases where the client makes a call to the server and expects a single, timely response, another API controller should be used. Furthermore, as the transport methods utilized by SignalR are not 100% reliable, it should never be used in a situation where the data being transferred to or from the server is of vital importance.

When deciding whether or not to utilize SignalR for a particular piece of functionality within your application, consider this rule of thumb: if a user would otherwise be required to refresh the page in order to see what has changed, use SignalR to notify the client of that change in real time instead.

Implementation

The easiest way to begin using SignalR in either an existing solution or from scratch is to dive straight in! From a bird’s eye view, this will consist of adding four primary components to your project: server-side, there’s ① a Hub class and ② an OWIN Startup class; client-side, there’s ③ HTML with JavaScript references and ④ the connection script.

Part 1: Hub Class

The SignalR library offers two base classes that enable duplex communication with client(s) or group(s) of clients: PersistentConnection, which exposes the basic SignalR service over HTTP, and Hub, which allows for the server and client(s) to make remote procedural calls (RPCs.) In most cases, the featureful Hub class is preferred, as using PersistentConnection will likely require you to reinvent the wheel in order to achieve the desired functionality.

If you’re using Visual Studio 2013, creating a Hub is as simple as adding a new class to your project and selecting the SignalR Hub Class (v2) template.

With Visual Studio 2012, there a couple of additional steps before you can start using SignalR. First, you’ll need to install the Microsoft ASP.NET SignalR package using NuGet; alternatively, open your package manager console (Tools > Library Package Manager > Package Manager Console) and execute the command:

*     install-package Microsoft.AspNet.SignalR*

Once the SignalR library is installed, add a new class to your project using SignalR and extending the Hub class. It should look something like this:

namespace MySignalRProject { using Microsoft.AspNet.SignalR; public class MyHubClass : Hub { public void Send(string name, string message) { Clients.All.broadcastMessage(name, message); } } }

As an example, when the Send() method above is called remotely by the client, it will echo the string parameters back to all connected clients via a broadcastMessage() function, which will be detailed in Part 4.

Part 2: Startup Class

Next, create an OWIN startup class if you don’t already have one in your project. OWIN (Open Web Interface for .NET) abstracts the web server within your application, allowing SignalR to act as middleware.

Once again, in Visual Studio 2013 this step is as easy as adding a new class using the Owin Startup Class template.

In Visual Studio 2012, add a new class named Startup, using Owin, and implement a Configuration method resembling the one below:

namespace MySignalRProject { using Owin; public class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } } }

Part 3: HTML

Now you’ll need client code to make use of the SignalR Hub added in Part 1 and exposed in Part 2. If you don’t already have a page view where you want to use SignalR, add an HTML file to your project and set it as the startup (right click, Set as Start Page.)

In addition to boilerplate references to jQuery and the SignalR library, you’ll include a script automatically generated by the Hub and a custom script that will be created in Part 4:

Part 4: JavaScript

Lastly, you’ll add the JavaScript file referenced in Part 3. Using jQuery to execute an anonymous function when the page loads, this script will establish a permanent connection with your SignalR Hub and define the behavior when receiving broadcast messages from the server:

$(function () { var myHub = $.connection.myHubClass; myHub.client.broadcastMessage = function(name, message) { // Code within this function will be executed // when a message is received from the server. }; $.connection.hub.start().done(function () { // Code within this function will be executed // after the hub connection is established. }); });

The Send() method created in Part 1 can be triggered remotely by the client using the corresponding server.send() function:

myHub.server.send('name', 'message');

By now you can start to see just how powerful SignalR’s Remote Procedural Calls can be. Deceptive in their simplicity, they ultimately allow for the seamless unification of server and client. Just remember, before you decide to convert your entire API over to SignalR, that it should be used only when appropriate, as prescribed in the Use Cases section above.

Have fun!

Additional Resources

*Official SignalR Project Website
*
http://signalr.net/

*Microsoft ASP.NET SignalR Website
*
http://www.asp.net/signalr

*SignalR Documentation on GitHub
*
https://github.com/SignalR/SignalR/wiki

*Installing NuGet Package Manager
*
http://docs.nuget.org/docs/start-here/installing-nuget

erland-kelley

I am a software developer and web/graphic designer specializing in UI/UX. I have over ten years of experience in a variety of industries, ranging from education and non-profit to e-commerce and