SignalR - Simple Chat Application in C#

SignalR Overview

Hello friends, today I am going to explain to you how to create a simple chat application using SignalR. Before looking at the code and understanding, let's try and understand what "SignalR" is.

SignalR is nothing but an Asynch Library which can be used to develop web applications and those applications provides some services which runs asynchronously. In other terms, SignalR is a library which can be used to create Real Time applications. In general terms, I feel the term "Real Time" means something or some event that actually happens with us at a particular time. Well, then "Real Time" in terms of a web application would mean "An immediate response sent by the Server on the Client's request".  There is a brief explanation of the term Real Time here...

Alright now moving towards SignalR, earlier it was not a part of the ASP.Net Family, but now Microsoft has incorporated it into VS 2012 and the .Net Framework 4.5. You can download the package here "Microsoft Asp.Net Fall 2012 Update BUILD Release". Checkout the Overview section before downloading the package.

SignalR is a library which is supported only by .Net Framework 4.0 and 4.5. So if you are one of those unlucky guys that want this library but are still working uing .Net Framework 3.5, it's now high time to switch to the latest framework version.

How does SignalR works?

You might have heard about some more terms like "Long Polling" or "Forever Frames" or "Web Sockets" or "Server Sent Events", if not then stay tuned for my next article on all these topics. Let me say those terms are "Concepts".
These concepts are used to create a persistent connection with the server and allow the client to interact with a Server. But there are a few drawbacks with each of these concepts. Well, I am not going to write about it in this article though. So SignalR is a new Concept / Technology which has overcome the problems associated with these concepts.

The most important funda behind using any of these concepts is to create a connection with the Server and do the required work. Well, with SignalR it basically makes use of all of these concepts, but depending upon the Client. Now "Client" here is nothing else but the user's browser. So if a user sends a request and tries to connect to the Server, SignalR first checks what kind of support this Client gives; whether it supports "Web Sockets" or "Forever Frames" depending upon the support, SignalR makes a persistent connection between the Server and the Client.

This connection is not just for a few minutes or seconds. It remains persistent until the user shuts / closes the browser explicitly. Here a few other, very important entities are relevant; they are "Hubs" and "Clients". I won't explain them here, but definitely will add it to my next article on SignalR.

The following is an overview of the interaction between the Server and the Client.

SignalR Interactions

SignalR-Sample-Cha- Application1.jpg


Explanation - In the image, the Client sends requests to the Server. The Server, using SignalR, checks if the Client supports any of the following data transportation techniques:

1. Web Sockets

2. Forever Frames

3. Server Sent Events

4. Long Polling

If the Client supports any of these techniques, the Server creates a connection between them and starts a conversation (Request - Response action).


My Chat Application: Alright, by now you definitely might have have an overview of "SignalR". Now it's time to have a look at the Sample Chat Application. I have created this application using .Net Framework 4.0 and Visual Studio 2010. Since I don't have VS 2012 I cannot download the fall package.
But no need to worry, there is another way to add the SignalR Library to your application. The following are the steps for installing the library to your application.


 I have created a simple "Empty Web Application"

1. Click on "File" and Select "New Project".

SignalR-Sample-Cha- Application2.jpg

2. The "New Project" window opens up. In the left panel, select your preferred language and select "Web". I love C# and hence this project is created using C#. Just         give your project a name and click on "Ok"

SignalR-Sample-Cha- Application3.jpg

3. Now Visual Studio will load your project and your application will be created something as shown in the image below. Now its time to add the SignalR package. So just right-click on the "References" folder and select "Manage NuGet Packages". If you do not have the "Nuget manager", then you can download the library using the Package Manager Console... Click here.

SignalR-Sample-Cha- Application4.jpg

4. After clicking on the "Manage Nuget Packages", a window will popup, Check the image below – Select "Microsoft ASP.NET SignalR" and click on "Install".

SignalR-Sample-Cha- Application5.jpg

5. Now the installation begins and the window should look something like this:

SignalR-Sample-Cha- Application6.jpg

6. During the Installation, the liscense window pops up. Just click on "I Accept" Button.

SignalR-Sample-Cha- Application7.jpg

7. Once the installation is completed, the final window will look something like this:

SignalR-Sample-Cha- Application8.jpg

8. The following jQuery file will be installed in your application; see the "Solution Explorer" in the image below:
SignalR-Sample-Cha- Application9.jpg

9. And the following references will be added. Check the Solution Explorer on the right side in the image below:

SignalR-Sample-Cha- Application10.jpg

So this was about the installation process. Now let's have a look at the Sample Chat Application.

The following are the 3 files that I added to my application :

  1. C# Class file – "LetsChat.cs"
  2. Web Form – "Chat.aspx"
  3. Global.asax

For this application there is hardly any code on the Server side. So before starting with the code, I added the following line of code in the Global.asax file.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.SessionState;

using System.Web.Routing;

using Microsoft.AspNet.SignalR;

 

namespace SignalRChat

{

    public class Global : System.Web.HttpApplication

    {

 

        protected void Application_Start(object sender, EventArgs e)

        {

            RouteTable.Routes.MapHubs();

        }

 

        protected void .......

The above line in the "Application_Start" section basically initializes the default hub. In our application, we have created a class called "LetsChat.cs" which derives the Hub Class. So whenever the application starts, then it maps to this class automatically.
 
C# Class File – LetsChat.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using Microsoft.AspNet.SignalR.Hubs;

 

namespace SignalRChat

{

    [HubName("myChatHub")]

    public class LetsChat : Hub

    {

        public void send(string message)

        {

            Clients.All.addMessage(message);

        }

    }

}
 
Explanation of the above Code – This class derives the Hub Class. We have 1 method called "Send" which accepts one parameter. This method is then called on the Client side and using the "
Clients.All.addMessage(message);" the message is sent to all the clients who are connected to this Chat.
 
"Clients" is a property which is a part of the Hub class and represents the actual Clients. In Clients, we have some more methods and properties which are displayed as follows:

  1. Clients.All - This represents all the Clients, so whenever a message is sent, then that message is received by all the connected clients.

    SignalR-Sample-Cha- Application11.jpg

  2. Clients.Caller - This will basically send a message or data only to the caller. It means whoever sends a message, only that person will receive it. It won't be received by any other connected clients.

    SignalR-Sample-Cha- Application12.jpg

  3. Clients.Others - Here other than the Caller, the message will be posted to all the connected clients.

    SignalR-Sample-Cha- Application13.jpg

  4. Client.Group() - This function is used to send messages or information to a certain group. In simple terms, this method allows you to create your own group and send information only to that group.

There are many other such functions which we can used to enrich our application. Wanna know, how to use them in proper terms??? Click here to learn more... SignalR
 
Finally in the above .cs file, if you have noticed, we have declared one attribute "
[HubName("myChatHub")]". This basically defines / represents our hub and is used in our Client code. 
 
Web Form – "Chat.aspx"

In the Web Form we have to link to the jQuery files:

SignalR-Sample-Cha- Application14.jpg

Script within the <body> tag:

SignalR-Sample-Cha- Application15.jpg
 
Explanation

  1. If you remember, we had mentioned the Attribute name ""myChatHub"". So in this Client side code, the Hub is referenced by this first line "var IWannaChat = $.connection.myChatHub;"
  2. In the second line of code, we are actually telling the Hub.Client.addMessage to take the message and append (list) it in the listMessages tag. "listMessages" is an ID being given to the <ul> tag.
  3. The third line takes the input from the textbox "txtMessage" and sends it to the Server. This information is then sent to the Client and displayed to all the connected users / clients.
  4. And finally with the last line of the code, we are actually starting the connection with the Hub.

You can see the entire code in the image below. I have also attached my project with this article so that you can download it and try it out.
 
Final - Chat.aspx

SignalR-Sample-Cha- Application16.jpg

C# Class – LetsChat.cs

SignalR-Sample-Cha- Application17.jpg

Here is the final output of the entire application:

  1. In this image, I have written the content "C# Corner Rocks" which is again displayed on the other browser. The reason is because there is a persistent connection between the Server and the Client and the way the information is sent from IE is using "Forever Frames".
    Here "IE9" acts like 1 Client and "Google Chrome" as another:

    SignalR-Sample-Cha- Application18.jpg

  2. In this image, I have written a message in Google Chrome and is displayed on IE at the same time.

    SignalR-Sample-Cha- Application19.jpg

Here the information is sent using the "Server Side Sent Events" transport way.
 
So this was my first article on SignalR. Hope you liked it and please do not forget to post your comments after reading the entire article.

Up Next
    Ebook Download
    View all
    Learn
    View all