QA InfoTech » Dot Net » Introduction of SignalR (Real Time Solution for Chat App)

Introduction of SignalR (Real Time Solution for Chat App)

IMPORTANCE :- Increase in the amount of data and availability, we need technologies to achieve this. For example, when in stock market prices are changing in each moment, do you think that user should refresh page every moment to inform the last price? it is not a reasonable solution for such a problem. SignalR is a real time web technology which uses set of asynchronous library to make a real time connection between client and server. User can receive latest updated data from server without refresh page manually or automatically each time.

AREA OF USES :- Chatting Applications, dashboards, real time monitoring applications, collaborative applications (document sharing applications used by 2 users), job progress updates, real-time forms, real-time gaming much more.

PROTOCALS USED :- First choice of SignalR is Websocket. However signalR checks both web server and client whether they support websocket or not, other wise it will attempt to use other protocols.

  • WebSocket :- WebSocket provides full duplex channel over a single TCP connection with encrypted messages. Feature of Websocket are most efficient use of server memory, has the lowest latency, and has the most underlying features like full duplex.
    Browser Support :- Google Chrome (> 16) Fire Fox (> 11) IE (> 10) Win IIS (>8.0) and partial implementation in other browsers such as Opera and Safari.
  • Server Sent Events (SSE)/EventSource :- Next choice of SingalR is SSE due to it’s persistence nature. It is a part of HTML5 Technology.                                                                                                                                                                                                                    Browser Support :- All browser except Internet Explorer.
  • Forever Frame :- When client sends request to server, then server sends a hidden iframe to client. This iframe is responsible to keep connection between client and server forever. Whenever server changes data, then send data as script tag to client (hidden iframe) and these scripts will be received sequentially. The connection from client to server uses a separate connection from the server to client connection, and like a standard HTML request.                                                                                                                                                    Browser Support :- Only Internet Explorer.
  • Ajax long polling :- Long polling does not create a persistent connection, but at which point the connection closes, and a new connection is requested immediately. This may introduce some latency while the connection resets.

For Support information, please see “http://www.asp.net/signalr/overview/getting-started/supported-platforms”.

signalr

Connections and Hubs

The SignalR API contains two models for communicating between clients and servers: Persistent Connections and Hubs.

A Connection represents a simple endpoint for sending single-recipient, grouped, or broadcast messages. The Persistent Connection API (represented in .NET code by the PersistentConnection class) gives the developer direct access to the low-level communication protocol that SignalR exposes.

A Hub is a more high-level pipeline built upon the Connection API that allows your client and server to call methods on each other directly. Using a Hub also allows you to pass strongly typed parameters to methods, enabling model binding.

Prerequisites
  1. Visual Studio 2012+
  2. SQL server 2008+
  3. Install necessary dependency from package manager console

Step 1:– Create MVC project by

File –> New Project –> ASP.Net MVC 4 Web Application { Give Name and Directory} –> { Template=Basic & View Engine=Razor }

Step 2:- Install Nuget packages

Menu (Tools) –> Library Package Manager –> Package Manager Console → Install-Package Microsoft.AspNet.SignalR

Step 3:- Add a startup class to configure SignalR route when the application starts.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // Any connection or hub wire up and configuration should go here
        app.MapSignalR();
    }
}

Step 4 :– Now create a Hub Class, provides the server functionality for the application.

public class ChatHub : Hub
{
    public void Send(string name, string message)
    {
        // Call the addNewMessageToPage method to update clients.
        Clients.All.addNewMessageToPage(name, message);            
    }
}

Step 5 :Now add a chat.cshtml class as a JavaScript client, which interacts with the server

<h2>Chat</h2>
<div class="container">
    <input type="text" id="message" />
    <input type="button" id="sendmessage" value="Send" />
    <input type="hidden" id="displayname" />
    <ul id="discussion"></ul>
</div>
@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.0.3.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.-->
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.
            var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page.
                $('#discussion').append('<li><strong>' + htmlEncode(name)
                    + '</strong>: ' + htmlEncode(message) + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>

Now your sample chat application is ready to work.

 

About the Author