March 28, 2013

How to use Signal R

So I played with SignalR a long while ago in one of it’s beta phases. I came back to it and found it completely different. With this post, I plan to talk about SignalR 1.0.1 and how to use it. 🙂

So SignalR creates a QUICK F**KING Pub Sub with ease. Now most people I have talked to have said it scales like crap and is not ready for primetime enterprise just yet, but I do find it valuable for smaller use cases. So let’s start off with some things to do first with Signal R:

 protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteTable.Routes.MapHubs(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } 

So basically start off by creating an MVC 4 app, and head to the global.asmx. There, you will want to add the RouteTable in line 2. This says that you want to route Hubs, but you might ask where? Well we will find out where later, but next let’s create a new folder called SignalR off the root of the project. Not in the Views or Controllers, just the root.

Once that folder is created, create a class and inherit Hub, like below:

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR; namespace BLT.SignalR { public class BaconJob : Hub { public const string key = "Server:{0}Job:{1}"; public void Distribute(string server, string job, string message) { Clients.Group(string.Format(key, server, job)).receive(message); } public void Join(string server, string job) { Groups.Add(Context.ConnectionId, string.Format(key, server, job)); } } } 

This code is creating 2 server calls for SignalR, Distribute and Join. Join will add a client to a topic, like a subscription. Distribute method will cause a message to distribute to all the clients associated with the key.

Next, let’s add this javascript to our page:

 

And add this HTML:

  

So that route you created before in the global.asmx; this allows the SignalR javascript to find the hubs and communicate. In the previous version of SignalR there was no “server” property and all the objects were dynamic. So, despite all the changes, it works the same….Yay!!!! Have fun.