Working With SignalR 2

SignalR is a technology used to create real-time functionality to applications. The term real-time is the ability to get the content to the clients instantly from the server. It doesn’t wait for the client to request the data. This can add any kind of ‘real-time’ web functionality to your Asp.Net application. You can perform any kind of operations related to real-time functionality, here we are using a discussion page where users are connecting just for any discussion.

Introduction

SignalR is a technology used to create real-time functionality to applications. The term real-time is the ability to get the content to the clients instantly from the server. It doesn’t wait for the client to request the data. This can add any kind of ‘real-time’ web functionality to your ASP.NET application. You can perform any kind of operations related to real-time functionality, here we are using a discussion page where users are connecting just for any discussion.

The application requiring this functionality can use the functionality of SignalR to add the real-time behavior to the app. It doesn’t need the page to be refreshed for any new data or any Ajax call to get the updated data to display just by calling the service internally. This is a very simple and lightweight technique to update the client for any new pushed data.

You can use the real-time behavior for gaming applications, kiosk machines, and any embedded system. This provides a simple API for creating a server to client RPC that calls the Javascript function in a client-side browser from the server. All the management for connection maintenance, and disconnecting from apps is done by SignalR API.

Prerequisite

  1. Programming of C#.
  2. Knowledge of JavaScript and Jquery.

Implementation

  1. Open Visual Studio.
  2. Create a new project.
  3. Enter the project name and select location.

    SignalR

  4. Select Empty from templates.

    SignalR

  5. Add SignalR to your project

Goto Tools - Library Package Manager - Package Manager Console.

Run the below command.

install-package Microsoft.AspNet.SignalR

If you have added the SignalR from the console, then create the SignalR hub class as separate after you add SignalR.

Add the signalR hub class ChatHub.cs and replace the content as below,

  1. using System;  
  2. using System.Web;  
  3. using Microsoft.AspNet.SignalR;  
  4. namespace SignalRChat  
  5. {  
  6.     public class ChatHub : Hub  
  7.     {  
  8.         public void Send(string name, string message)  
  9.         {  
  10.             // Call the broadcastMessage method to update clients.  
  11.             Clients.All.broadcastMessage(name, message);  
  12.         }  
  13.     }  
  14.        }  

SignalR Hubs

The Hub class is used to build the SignalR application.

The Send method of ChatHub class demonstrates several hub concepts :

  • We can declarea public method which is being called by the client.
  • We use Microsoft.AspNet.SignalR.Hub.Clients  dynamic property to access all clients connected to this hub.
  • Call a function on the client (such as the broadcastMessagefunction) to push any update to the connected client.

    Add the StartUp.cs class and add the below content,
    1. using Microsoft.Owin;  
    2. using Owin;  
    3. [assembly: OwinStartup(typeof(SignalRChat.Startup))]  
    4. namespace SignalRChat  
    5. {  
    6.     public class Startup  
    7.     {  
    8.         public void Configuration(IAppBuilder app)  
    9.         {  
    10.             // Any connection or hub wire up and configuration should go here  
    11.             app.MapSignalR();  
    12.         }  
    13.     }  
    14. }  
  1. Add myScript.js under Scripts directory and add the below content.
    1. $(document).ready(function () {  
    2.     $('#container').hide();  
    3. });  
    4.   
    5. function startDiscussion() {  
    6.   
    7.     // Declare a proxy to reference the hub.  
    8.     var chat = $.connection.chatHub;  
    9.     // Create a function that the hub can call to broadcast messages.  
    10.     chat.client.broadcastMessage = function (name, message) {  
    11.   
    12.         var encodedName = $('<div />').text(name).html();  
    13.         var encodedMsg = $('<div />').text(message).html();  
    14.   
    15.         $('#discussion').append('<li><h4>' + encodedName  
    16.             + '</h4>:  ' + encodedMsg + '</li>');  
    17.     };  
    18.     $('#message').focus();  
    19.     $.connection.hub.start().done(function () {  
    20.         $('#sendmessage').click(function () {  
    21.             chat.server.send($('#displayname').val(), $('#message').val());  
    22.             $('#message').val('').focus();  
    23.         });  
    24.     });  
    25. }  
    26.   
    27. function AddUser() {  
    28.     if ($('#username').val() == "") {  
    29.         alert('enter username');  
    30.         return;  
    31.     }  
    32.     $('#displayname').val($('#username').val());  
    33.     $('#container').show();  
    34.     $('#setUser').hide();  
    35.     startDiscussion();  
    36. $('#welcome').append(" : " + $('#username').val());  
    37. }  
    Note
    The code above is the sample reference of C# ChatHub class in above JS as chatHub as we use in camelCase.
  1. Add index.html and add the below contents,
    1. <!DOCTYPE html>  
    2. <html>  
    3. <head>  
    4. <style>  
    5. </head>  
    6. <body style="background-color: sienna">  
    7. <h1>XYZ Discussion!</h1>  
    8.     <div class="container" id="container">  
    9.         <h2>Welcome to Discussion.</h2>  
    10.         <input type="text" id="message" />  
    11.         <input type="button" id="sendmessage" value="Send" />  
    12.         <input type="hidden" id="displayname" />  
    13.         <ul id="discussion"></ul>  
    14.     </div>  
    15.     <div id="setUser">  
    16.         <input type="text" id="username" placeholder="Enter your name"/>  
    17.         <input type="button" onclick="AddUser()" value="Join Discussion" />  
    18.     </div>      
    19. </body>  
    20. </html>  
  1. Directory structure will be as follows,
    SignalR

Let us run the application and see.

Note

  1. For testing purposes open the same url in two tabs.
  2. I have entered two names, “Irshad” and “Imran” for discussion.
  3. Sent message from any user will be notified to all the open tabbed clients.
  4. You can see the below images.

    SignalR

    SignalR
    SignalR
    SignalR
    SignalR
    SignalR
    SignalR