Building Real time application with SignalR – Part 1

Brij Bhushan Mishra / Thursday, February 4, 2016
HTTP protocol is the basis for all communication over the web, and it has catered to our needs since the early days. HTTP works in a request and response model, where a request needs to be sent to the server to get any update from there. This creates challenges in handling a few scenarios where we need real time data: when a user opens a web page then it needs to be updated, and when there is a change on the server but as per the HTTP architecture, a new request must be sent to get an update from the server. This creates a bad experience for the user and multiple requests may throttle the network bandwidth as well. There are many real-time scenarios where we need to show live data to the user (such as with Stock Market info, Live Game results, chat applications and others). 

To handle these scenarios we use different workarounds, which AJAX helped with a lot. AJAX allows us to send a request (relatively very small) and update the UI based on the response. Other challenges we face include the different behavior of browsers in terms of features and support. From a performance point of view, the server’s resource and network utilization are other issues, so we can’t blindly send multiple requests to the server. Similarly we can’t make the user wait more while waiting for the update. It’s developer’s responsibility to use the best available option/protocol for handling real-time communication.

What is SignalR?

SignalR is a high level library which makes the development of real time web applications super easy. We can write real time web applications using AJAX like discussed above, or we can use Forever Frame or some other custom workarounds, but these are pretty complex and different logic is needed for different scenarios. SignalR hides all the complexities involved and works seamlessly on all the browsers including different versions. It is very powerful and allows bidirectional communications between client and server. The server is not required to wait for the request of the client to send the response, instead it can logically push the response when new data is available. It handles the connection management itself and enables us to broadcast/unicast messages to the connected clients.

Transport mechanism

SignalR uses one of multiple technolgies to set up communications between client and server. Web Socket, which was introduced with HTML5, provides bidirectional support but it is not supported by all the browsers and older versions. As we can’t guarantee what browser will be used by the user, we can’t simply rely on this, so there must be some way which can implement similar features across browsers. To do t his, SignalR allows you to use multiple transport technologies and select one which is most suitable for the scenario.

 

 

Let’s discuss the above technologies briefly.

 

Web Socket – This is a new communication technology which provides a true two-way communication over a single TCP connection on web. In other words, if both the parties (Client and server) supports web socket, then this creates a persistent connection between them which can be used by either client or server to send the data anytime. As such, this is most efficient, takes less memory and shows the lowest latency. This is the most preferred protocol for a SignalR application.

Server Sent Events (also known as Event Source) – This is another technique introduced with HTML5 which allows the server to push the updates to the client whenever new data is available. This technology is used when Web Socket is not supported. It is supported by most browsers except IE. 

Forever Frame – This is part of the COMET model and uses a hidden iframe on the browser to receive the data in an incremental manner from the server. The server starts sending the data in a series of chunks even without even knowing the complete length of the content. It is executed on the client when the data is received.  

AJAX Long Polling – This is the least preferred way in SignalR to set up a communication between Client and Server. Also, it is the most expensive amongst all, too! It is a part of the COMET model and as the name suggests, it keeps polling the server to check for updates. The request that is sent to the server is AJAX based, to minimize the resource usage and provide a better user experience. But it’s still expensive because it keeps polling the server whether there are any updates or not.

Before moving further, let’s discuss the two different models used to connect between Client and Server: Persistent Connection and Hub

Persistent Connection – This is a lower level API which allows us to send raw messages to different clients. We can also customize this based on the different types of messages and different clients, and can send these details with the message as well. In simple words, on one hand it gives us more control over connecting and sending different types of messages, while on the other hand we need to write more code.

Hubs – These are higher level APIs which are built on top of the Persistent connections. Hubs hide all the complexities from the developer and provide us a simple RPC style model with the unique function defined. 

How to use SignalR

SignalR is fairly easy to configure and use. We can just install the nuget package as follows:

 

 

 

Or we can run the following command via Packet Manager Console:

 

Install-Package Microsoft.AspNet.SignalR

 

 

This installs all the required components of SignalR. Once installed, to start using it, we need to complete the following steps:

 

1-    First, we need to configure in our application. For that we need to create a class named as Startup.cs and put the following code there:

 

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }

    }

 

2-    Create a Hub class which should inherit from Hub class as:

 

public class MySignalRHub : Hub

{

    public void SendMessage(string message)

    {

        // Calls the call back function defined on client side

        Clients.All.SayHello("Hello !! Your Message : " + message);

    }

}

 

The Hub is the core of any SignalR application and it is the Hub which facilitates the communication between client and server. Here the SayHello method is a JavaScript method (we will see next) which is called from the Hub. The SendMessage method will be called from the client. The hub provides the model binding and serialization out of the box.

 

3-    Now on client side (say in Index.HTML), we need to add flowing libraries:

<script src="Scripts/jquery-1.6.4.min.js">script>

<script src="Scripts/jquery.signalR-2.2.0.js">script>

The above are jQuery and SignalR libraries which are required for a JavaScript client. The minimum version of jQuery is 1,6.4.

 

4-    Now how does the client connect to server method? For that we need to include the Hub proxy which is dynamically generated. Using this, the communication happens between the server and client. It is included as:

<script src="signalr/hubs">script>

Note – The order of the file on the client should be same as jQuery, jQuery SignalR and Hub proxy.

 

5-    We have all the required resources on the client. Now we need to write the code for calling the server side code and provide a call back function which would be called from server when the server gets any update. Let’s see that in code:

 

var hubproxy = $.connection.mySignalRHub;

 

This is the proxy instance which would be key for communication. Let’s define the callback method as:

 

hubproxy.client.sayHello = function (message) {
 
    // Process your message

}

 

Now to call the server side method as:

 

$.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    hubproxy.server.sendMessage($('#tbmessage').val());                
                });

            });

 

In the above code, there are two key things. First we are starting the hub and when it is done then we are only adding the click method and calling the sendMessage of the hub. This cannot be called before starting the hub.

 

The above are all the steps required for the minimum setup of a SignalR application. Let’s see the pictorial representation of the communication between client and server here:

 

 

Note – At the client side, we’ll need to call the method regardless of how it is written at the server, or else it won’t be called.

 

Conclusion

In this post, we discussed the complexities of writing real time web applications and how SignalR simplifies that process. Then we discussed the concepts of connection models, transport models and how to set up the infrastructure and get started with SignalR. Stay tuned for my next post, where we’ll cover the insights of SignalR with a real life example.

 

Create modern Web apps for any scenario with your favorite frameworks. Download Ignite UI today and experience the power of Infragistics jQuery/HMTL5 controls.