A simple SignalR message broadcaster

I know every one already knows what SignalR is and how awesome it is. If you don’t, it can be described simply …. a mechanism for sending messages to the web clients (browsers) from the server and visa versa. It does this via the magic of web sockets*.

*in IE8 and below it uses old school polling, but SignalR will deal with that.

I was building a mechanism for telling the users that an update to the site was about to occur and to save their work, in effect a broadcast system. Even though this is easy and requires very little code, I thought I would have a look to see what samples of SignalR are out there. I could only really find chat systems, so I thought I would put up this, the most basic of examples, which is a nice way to start playing with SignalR.

1. Nuget SignalR

Install-PackageMicrosoft.AspNet.SignalR

2. Include script (preferably in bundles)

script src= "~/Scripts/jquery.signalR-2.1.0.min.js" ></script>
<script src= "~/signalr/hubs" ></script>

3. Add the script to your page (global or local)

$(function () {
var centralHub = $.connection.signalRHub
$.connection.hub.start ();
centralHub.client.sendMessage = function ( id, message ) {
//this is the display bit
alert (message);
//or replace an element or anything at all
}
});

4. Build you hub (if using IOC ensure you use a singleton type instance)

public class SignalRHub : Hub {
    public void SendMessage(string message) {
        var context = GlobalHost.ConnectionManager
                .GetHubContext < SignalRHub> ();
        context.Clients.All.sendMessage("MsgFromServer", message);
    }
}

5. Add the signalR starter by right-click -> Add item -> ‘OWIN startup class’ and replace with the following code

using Microsoft.Owin;
using Owin; 
[assembly: OwinStartup(typeof (Application.SignalRHubStartup))]
namespace Application{
    public class SignalRHubStartup{
        public void Configuration(IAppBuilder app){
            var mapped = app.MapSignalR();
        }
    }
}

6. Call like normal (if using IOC ensure you use a singleton type instance)

var signalR = new SignalRHub();signalR.SendMessage(message);

The message you pass will be used in the alert at the top of each client.

Obviously this can also be used to go from client to hub (server) -that is why all the examples are chat systems as it lends itself to that well.
SignalR website

Leave a comment