Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Introduction to Signal-R

0.00/5 (No votes)
8 Dec 2014 1  
In this tip, we will go step by step on understanding of Signal-R.

Introduction

It's been long since I have been searching for a good and working Signal-R blog, but trust me there are none. Some are marginally good but again, the code they offer do not work. After lot of concept seeking and code searching, I am finally able to create a working demo. In this blog post, we will go in a step by step manner to understand what Signal-R is.

What is SignalR

If client needs data from server, it simply pings server and asks for data. But there are cases when client needs to constantly ping server to see if server has any data of its interest, if yes, client fetches the data and if no, it will ping the server again. Let’s not get confused about this, let’s go through an example to rather simplify the situation.

Imagine your mom asks you to bring some groceries back home when you return. You know moms are so impatient, and you can trust on that. On the same evening, when you are on the way back she would continuously ring you and remind you that you need to purchase groceries, you need to purchase groceries, you need to purchase groceries…You can say yes to any one of the calls if you have bought it already, else your answer would be no.

Consider the same scenario where instead of your Mom, your Dad has given you same task. He won’t ping you constantly to inspect whether or not you are done, but instead you have to call him back once you are done purchasing.

In the above analogy, if you consider yourself a server and your parents as Client, the later communication with Dad is called as duplex communication and the former with Mom is simplex communication. In duplex communication, not only client can ask server for data, server could also ping its client with the set of data it has.

There are various other techniques you can use to attain this, in this blog however, we would be focusing on the aspects of Signal-R.

Getting Started

To get started, we need to first create an empty ASP.NET website and here we go.

empty ASPNet website

Once the Web Site is created, go to solution explorer –> Right click on project and choose "Manage Nuget Package".

Manage Nuget Package

When the Packet manager Window is opened, search for the signal-r package.

signal-r package

Install the Microsoft ASP.NET SignalR package. When the Visual Studio is done installing the package, you are good to go. Add two classes and one HTML page after that in the solution.

  • ChatHub.cs
  • Startup.cs
  • index.html

ChatHub Class

This is what I have in my class:

 using Microsoft.AspNet.SignalR;  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Threading;  
 using System.Web;  
  
 namespace MySignalRDemo  
 {  
  public class ChatHub : Hub  
  {  
     /// <summary>  
     /// Send the value to the server after every two seconds  
     /// </summary>  
     public void Send()  
     {  
         // Call the broadcastMessage method to update clients.  
         for (int i = 0; i <= 100; i++)  
         {  
              //"All" is dynamic, and broadcastMessage is the method that we'll  
             //create in JavaScript at client side.  
             Clients.All.broadcastMessage(i.ToString());  
             Thread.Sleep(2000);  
         }  
      }  
    }  
 }

I have a method in my Class called “Send” you can have any method of any name in this class. But you must remember the name of the method because you have to call this method from JavaScript in the client. Notice also that the class is inheriting another class Hub. What it will do is, it would generate a JavaScript file which would have every method that the class inheriting class Hub has. For instance, in this case, the generated JavaScript file would have a method named Send(). We will look into more theory at the later stage but for now, what this class does basically is that it broadcasts messages every 2 seconds to all its clients.

Send

Startup.cs Class

This is what I have in my startup class.

 using Microsoft.Owin;  
 using Owin;  
  
 [assembly: OwinStartup(typeof(SignalRDemo.Startup))]  
 namespace MySignalRDemo  
 {  
     public class Startup  
     {  
         public void Configuration(IAppBuilder app)  
        {  
           // Any connection or hub wire up and configuration should go here  
           app.MapSignalR();  
        }  
    }  
 }

This class is kind of like a configuration that would help in routing the connection from server to client.

Index.html file

This is what my UI has:

<!DOCTYPE html>  
<html>  
    <head>  
        <title>SignalR BroadCast</title>  
    </head>  
    <body>  
        <div class="container">  
            <h1 id="message"></h1>  
        </div>  
        <!--Script references. -->  
        <!--Reference the jQuery library. -->  
        <script src="Scripts/jquery-1.6.4.min.js" ></script>  
        <!--Reference the SignalR library. -->  
        <script src="Scripts/jquery.signalR-2.0.2.min.js"></script>  
        <script src="Scripts/jquery.signalR-2.0.3.js"></script>  
        <!--Reference the autogenerated SignalR hub script. -->  
        <script src="/signalr/hubs"></script>  
        <!--Add script to update the page and send messages.-->  
        <script type="text/javascript">  
          
        $(function () {  
            // Declare a proxy to reference the hub.  
            var chat = $.connection.chatHub;  
            //BroadcastMessage, the same method that we have set in  
            //Cleints.All.broadcastMessage()  
            chat.client.broadcastMessage = function (value) {  
            $('#message').text(value.toString());  
        };  
         
        $.connection.hub.start().done(function () {  
            //send, the same method that we have in our chathub class  
            chat.server.send();  
            });  
        });  
         
        </script>  
    </body>  
</html> 

In line #23, I have created a client of our ChatHub class in JavaScript. Next in line #26, I’ve created a method named broadcastMessage, the same method that we have in line #22 of ChatHub class. In chathub class, we are passing the values in the broadcastMessage method, which we are catching here and displaying on the UI.

When the connection with the server is established successfully, I have initiated the communication by calling the Send method of the server in line #32.

If you run the application now, it will show you the number count on the screen, which would update every 2 seconds.

screen

I hope this post would help you to understand Signal-R better.

You can download the project from MySignalRDemo.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here