Learn to use SignalR in a Web App

Carlos Gómez
devops and cross platform development
2 min readMar 25, 2015

--

SignalR is a library for ASP.NET that give us the possibility to add real-time functionality to our web applications.

The great advantage of use SignalR is that will use WebSockets under the covers when it’s available, and gracefully fallback to other techniques like Server Sent Events → Forever Frames → Long Polling this techniques depends on the client Browser.

SignalR different fallbacks  techniques

How to include SignalR in our project

Our starting point would be an ASP.NET project that has been already created and the steps to follow are:

Steps to include signalR in a web app
  1. We need to install the SignalR nugget package:
  • PM> Install-Package Microsoft.AspNet.SignalR
    PM> Install-Package Microsoft.AspNet.SignalR.JS
  1. Wire up SignalR using OWIN: Our Startup.cs must look like
  • [assembly: OwinStartup(typeof(Startup))]
    public class Startup
    {
    public void Configuration(IAppBuilder appBuilder)
    {
    appBuilder.MapSignalR();
    }
    }
  1. Include the jQuery Scripts in html: “The order is important!”
  • <!DOCTYPE html>
    <html>
    <head>
    <meta name=”viewport” content=”width=device-width” />
    <title></title>
    </head>
    <body>
    <script src=”~/Scripts/jquery-1.10.2.js”></script>
    <script src=”~/Scripts/jquery.signalR-2.0.2.js”></script>
    </body>
    </html>
  1. Create a Hub: We need to create a class that extends from Hub
  • public class HelloHub : Hub
    {
    public void SayHello()
    {
    Clients.All.hello(“Hello World!”);
    }
    }
  1. Connect the client to the Hub using JavaScript:
  • <!DOCTYPE html>
    <html>
    <head>
    <meta name=”viewport” content=”width=device-width” />
    <title></title>
    </head>
    <body>
    <script src=”~/Scripts/jquery-1.10.2.js”></script>
    <script src=”~/Scripts/jquery.signalR-2.0.2.js”></script>
  • <script type=”text/javascript”>
    $(function () {
    // create a signalr connection
    var con = $.hubConnection();

    // create a hub proxy
    var hub = con.createHubProxy(‘helloHub’);
  • // an event handler for a hub-generated event
    hub.on(‘hello’, function (greeting) {
    $(‘#counter’).text(greeting);
    });
  • // start the connection
    con.start.done(function () {
    // we’re connected now
    hub.invoke(‘sayHello’);
    });
    });
    </script>
    </body>
    </html>

For more information about SignalR go to the oficial page at http://signalr.net/

--

--

Cloud/Software Architect and DevOps learning about #devops, #cloud, #netcore, #microservices and #newtech