Real-Time Web Functionality Using ASP.Net SignalR

The HTTP protocol of the internet works on a stateless model and hence every time the client makes a request to the server to get data and once the server sends the response out to the client, the connection is closed, and there is nothing that the server can send over the connection to the client. Microsoft provides ASP.NET SignalR to do the real-time web functionality where the server can push the updates to the client when it has any. The client must first make a request to the servers to get the updated data.

The real-time communication uses techniques such as Polling, Long Polling and so on.

Real-time communication is most used in chat applications, gaming applications and many other monitoring applications like Stock Exchange applications for showing updates in the stock market every second.

HTML5 Web Sockets is also one of the techniques to do Real-time Communication and SignalR also uses Web Sockets under the hood to do this wherever Web Sockets can work, else it falls back to Long Polling and Polling techniques. One can use Web Sockets but the benefit we get by using SignalR is that while using Web Sockets you need to write a lot of code to do all the real-time functionalities whereas SignalR provides you with the API(s) for doing all of it. Also you don't need to worry while implementing SignalR if the client and server supports Web Socket Connections, if the connections are supported then SignalR will use Web Sockets under the hood and if not it will fall back to other techniques for achieving Real-time Communication.

SignalR provides APIs for managing the connections, connections from various clients, and also provides the ability of the server to push the messages to the client by calling the methods defined on the client-side in JavaScript using Remote Procedure Calls. Similarly, the client can also call methods on the server-side on the same established connection. The API that helps in doing so is known as "Hubs".

So you can use various Hubs in your application for the various real-time functionalities. So all the communication that will be done for a specific functionality will be defined in the Hub, and the code is responsible for handling any messages coming from the client and sent to the client.

Microsoft provides SignalR as a NuGet package that comes with all the server components required at the server-side and the JavaScript files required at the client-side for real-time communication. I will show you how to create a sample application using SignalR, I was just eager to write it down when I got a query in the comment on the article of HTML5 WebSockets, saying "Which one is better??" It's better to be late than never... :)
I hope this article will help to determine which one is better for them, if you are using Microsoft Technologies then I will recommend using with SignalR rather than Web Sockets, since it will save a lot of Development effort and will use Web Sockets under the hood, wherever it is supported.

For downloading the SignalR package, just open up the Package Manager Console and type in the following command:

PM> Install-Package Microsoft.AspNet.SignalR

For creating a sample application, I have created a sample Web site. Now download the SignalR package using the command above in the Package Manager Console.

As soon as you have downloaded the package you will see that some DLL(s) required for SignalR and some of the JavaScript files required at the client side are automatically added into your sample project or website, whatever you are creating.

ASP.NET SingalR

I will create a simple chat application that I also demonstrated while writing article about HTML5 Web Sockets, and here you will see the difference. If you compare both then you will see that SignalR has removed much of the coding effort by providing API(s) required for Real-time Communication.

Add a class in which we will write code for the communication between the client and the server. This class will be inherited from the Hubs class provided in SignalR API(s). In this class I created a method "SendMessage". This is the method to which the client will make a request to whenever it wants to broadcast a message for other users. And in this method we have written the code that broadcasts this message to all the clients by calling the "MessageRecieved" method on the client side. In the "MessageRecieved" method we will receive the message and we can use JavaScript to display this message by putting it into the HTML DOM.

  1. using Microsoft.AspNet.SignalR;  
  2. /// <summary>  
  3. /// Summary description for ChatHub  
  4. /// </summary>  
  5. public class ChatHub : Hub  
  6. {  
  7.     public void SendMessage(string message)  
  8.     {  
  9.         Clients.All.MessageRecieved(message);  
  10.     }  
  11. }   

Another class that is there is required for doing the configuration, the configuration of the Hub Configuration is like, if we need CORS in between or we want to enable a Cross Domain Request by enabling JSONP requests. So if you are using multiple Hubs then the entire configuration can go into this class. This class is the OWIN start-up class and we will define it as the OWIN start-up class by making the following entry into the "Web.Config" file.

  1. <appSettings>  
  2.     <add key="owin:appStartup" value="StartupClass"/>  
  3. </appSettings>  
Startup Class

  1. using Microsoft.Owin;  
  2. using Owin;  
  3. [assembly: OwinStartup(typeof(StartupClass))]  
  4. /// <summary>  
  5. /// Summary description for StartupClass  
  6. /// </summary>  
  7. public class StartupClass  
  8. {  
  9.     public void Configuration(IAppBuilder app)  
  10.     {  
  11.         app.MapSignalR();  
  12.     }  
  13. }  

And with this we are ready to go. I have created a sample page for demonstration.

Default.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6.     <script type="text/javascript" src="Scripts/jquery-1.6.4.min.js"></script>  
  7.     <script type="text/javascript" src="Scripts/jquery.signalR-2.0.0.min.js"></script>  
  8.     <script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>  
  9. </head>  
  10. <body>  
  11.     <form id="form1" runat="server">  
  12.         Message:  
  13.     <input type="text" id="txtMessage" /> <input type="button" id="btnBroadcastMessage" value="Broadcast" /><br />  
  14.         <div id="divMessages">  
  15.         </div>  
  16.         <script type="text/javascript">  
  17.             $(function () {  
  18.                 var chatHub = $.connection.chatHub;  
  19.                 $.connection.hub.start().done(function () {  
  20.                     $("#btnBroadcastMessage").click(function () {  
  21.                        chatHub.server.sendMessage($('#txtMessage').val());  
  22.                     });  
  23.                 }).fail(function (data) { alert(data) });  
  24.                 chatHub.client.MessageRecieved = function (message) {  
  25.                     $('#divMessages').append(message + '<br/>');  
  26.                 };  
  27.             });  
  28.         </script>  
  29.     </form>  
  30. </body>  
  31. </html>   

Running Sample

ASP.NET SingalR1

I think this has made it clear that it is so much easier to use SignalR, whereas one has to put a lot of effort into creating a similar application with Web Sockets. I am also attaching the sample code, that you can execute at your end and see the results. Yes much more can be done using configurations, writing down a small piece of code can help you in doing a lot; a Security API is also there for security purposes.


Similar Articles