Thursday, April 12, 2012

Developing Real time application with ASP.NET using Signal R


What is SignalR
From the GitHub website https://github.com/SignalR/SignalR
" Signal R is Async signaling library for .NET to help build real-time, multi-user interactive web applications. "
It is library developed by the David Fowler and Damian Edwards; which supports the asynchronous connection in ASP.NET and helps to build the real time web application using JavaScript at client side and ASP.NET at server side.
We know that in HTTP web application client makes request to the server and then server respond to the client; SO it is always from client to server. But there are certain situation where some happenings at server needs to notify to the client. So how do we achieve it? Previously we used to write JavaScript polling for this. But this polling is buggy and needs lot of error handling and it also not really real time it has some delay.

SignalR library provide this facility of notifying client when something happens at server.
SignalR uses Web Sockets and Logrolling whichever is best suited by the browser. 
You can find more information on Web Sockets and Logrolling here and here.

 Normal HTTP request response flow
Client makes request to server and server responds to the client.
Old age solution for notifying client

 
Client is making the request to the server after each timer interval; timer is implemented at client side
SignalR Async flow for notifying client
Client makes asycn request to the client; Server waits for some event to occur on occurring the event server notifies the all clients
Application development using SignalR library
SignalR has different component like
·         SignalR
·         SignalR.Server
·         SignalR.Js
·         SignalR.Client
To develop the ASP.NET real time web application we need to install SignalR package from Nuget. To do this run the following command in Package Manager Console

PM> install-package SignalR

Installed the SignalR from Nuget

Start VS2010 and create new Web Site project (File->New->Web Site..) and run the command to install SignalR package. After running the above command it will add SignalR references and SignalR JS to your application as shown below.
 
Create web site project

 
References of SignalR JS and SignalR dll
Server Side code
We will be developing chat application so let us add class with name Chat as shown below

Following are some notable points about the code
1.   This class file has reference to SignalR.Hubs.
2.   Chat class has attribute HubName "chat" this is very important and required; This says that this is a hub for the SignalR and SignalR JS client  shall call this class method.
3.   Chat class has one method Send with attribute HubMethodName "send"; This says that SignalR JS client calls this method asynchronously.
4.   Let us look at the implementation of the Send method this contain signal line
                   Clients.addMessage(message);
Here Clients is dynamic variable; and addMessage shall be resolved at a runtime. When this method is called subscribed method of the clients shall be get called.  
Client side code  
At client side create UI like shown below
   
It has one bullet list with id messages, one text box with id msg and one button with id broadcast as shown in the image above. 
Let us see the client JavaScript , Following is the JavaScript's are included.

 
1.   jquery-1.7.2.js This is required as SignalR JS  requires JQuery. Please make sure that you have latest version of Jquery included.
2.   json2.js This is required for working SignalR JS client in IE 8 + browsers.
3.   jquery.signalR.js This is SignalR JS client.
4.   Following line is most important
<script type="text/javascript" src='<%= ResolveClientUrl("~/signalr/hubs") %>'></script>
This is required because at run time SignalR creates JavaScript proxy for the server at the location ~/signalr/hubs; To create this proxy it uses the attributes given in server code. If you do not include this path or include it incorrectly SignalR will not find proxy and will not be able to run. you can look the proxy generated in browser by entering the URL <You server path>/signalr/hubs; as below
Let us see JavaScript written as follows
 

1.   First line var chat = $.connection.chat; creates connection to the server side Chat class. Please note that "chat" here is the same as the HubName attribute.


2.   Next Line
            $.connection.hub.start({ transport: 'auto' }, function () {
                // alert('connected');
            });

It opens the connection with transport auto and function specified there gets called once the connection is established.
3.   Next piece of code is
        $("#broadcast").click(function () {
                //                alert($("#msg").val());
                chat.send($("#MainContent_userName").text() + $("#msg").val());

                $("#msg").val('')
            });
This code is get called when user clicks broadcast button; and chat.send() method calls the server side Chat.Send method. Please note that "send" method here is same as the HubMethodName attribute in server side code.
4.   Next code
     chat.addMessage = function (message) {
                $('#messages').append('<li>' + message + '</li>');
            };
It specifies when server calls addMessage method then function should get called  this function displays message in bulleted list. Please note that we have added addMessage method to dynamic variable Clients in the server code.
So, Now you have developed the application What next? Let us run it. Run the application in two separate browser as shown below; Enter your name and click Enter Chat room button. For testing in both browsers I have taken one as IE and other as Firefox.

As soon as you type message in one window and click send button it will be displayed in both the window; you can try opening more windows.


You can find the running sample application here.




7 comments:

Gautam Bhandarkar said...

Very nice Sanket! I will try this myself!

Sobin said...

Great article ..

Will it work in all browsers including IE6?


BTW, Your captcha is nasty. If you replace it ,I promise ,comments will flow...

Harry Hampton said...

I like your post very much about .Net Development. The information in this post is very interesting and more useful for the developers. Thanks for share this valuable info.

Sanket Kulkarni said...

Thanks Sobin for your information about the captcha, I will try to replace it.

About IE6 SignalR does not work with IE6 as SignalR requires a JSON parser and ability to send xhr requests (for long polling). For more information https://github.com/SignalR/SignalR/wiki/Faq

Mohit said...

Sanket plz tell how to add reference of pakage which v hav downloaded and hav it in some folder in our system . Plz tell which folder to include while adding reference of in settings!
i hav signalR folder with many sub-folders.

SID said...

HI Sanket, Great Article, Though It Would Be really Nice if you updated your blog with the new MVC 4 implementation.

Unknown said...

Windows Azure application provides facilities like mobile apps development, social networking applications also in lot of other types of applications. In windows app development, Azure application full of performance.