Click here to Skip to main content
Click here to Skip to main content

SignalR - Simple Chat Application in C#

, 8 Jan 2013
Rate this:
Please Sign up or sign in to vote.
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.

All right 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

 

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: All right, 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".

     

  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"

  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.

  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".


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

     

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

     

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


  8. The following jQuery file will be installed in your application; see the "Solution Explorer" in the image below:
  9. And the following references will be added. Check the Solution Explorer on the right side in the image below:

     

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. This basically helps the Client Side call the Server Side functions.

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.

  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.

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

  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:

 

Script within the <body> tag:

 

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

C# Class : LetsChat.cs

 

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".
  2. Here "IE9" acts like 1 Client and "Google Chrome" as another:  

     

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

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!!!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Shivanand Arur
Software Developer
India India
I am a Software Engineer and a MINDCRACKER MVP and I like to work and create web applications. I love ASP.NET, C# and also love to explore the various features of these technologies. Microsoft's .Net technology and C# language are my true love. I am passionate in learning new things especially related to the .Net Technology.
 
My hobbies are to read technical articles and various Blogs, listening good music, Playing my guitar, Gaming(sometimes).... I have developed a new hobbie after joining C# Corner which is nothing else but "Writing Articles"....
 
Writing Articles is something which I have recently started and is really helping me to learn and explore various topics which I never thought it would be.... Anyways that's it for now.... Thanks for viewing my Profile Smile | :)
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionGreat work !!! PinmemberAmila thennakoon27-Apr-14 22:45 
GeneralMy vote of 5 PinprofessionalNirav Prabtani16-Apr-14 2:53 
SuggestionMy vote 3 PinmemberShail Mishra14-Mar-14 1:56 
GeneralMy Vote PinprofessionalMehdy Moini13-Dec-13 7:11 
QuestionNeed little guidance. Pinmember VICK10-Dec-13 19:24 
Questioninstallation problem PinmemberMember 1030997924-Nov-13 16:45 
AnswerRe: installation problem Pinmember VICK10-Dec-13 18:54 
GeneralMy vote of 5 PinprofessionalS.Sathik Ali2-Sep-13 21:29 
GeneralMy vote of 5 PinprofessionalSampath Lokuge7-Aug-13 5:06 
QuestionSignalR pure HTML Pinmemberyousefk21-Jul-13 1:52 
QuestionNice topic PinmemberADITYA SINGH RANA .10-Jun-13 4:25 
QuestionDoubt PinmemberMember 1005287415-May-13 2:53 
AnswerRe: Doubt PinmemberShivanand Arur15-May-13 3:27 
GeneralMy vote of 5 PinmemberYazanpro18-Apr-13 14:13 
GeneralRe: My vote of 5 PinmemberShivanand Arur18-Apr-13 21:15 
NewsReference PinmemberShahdat Hosain8-Mar-13 11:49 
Questionnice article Pinmemberashokruhela6-Mar-13 20:05 
AnswerRe: nice article PinmemberShivanand Arur6-Mar-13 22:39 
BugNo JSON parser found PinmemberEM1L14-Jan-13 6:00 
GeneralRe: No JSON parser found PinmemberShivanand Arur14-Jan-13 16:41 
SuggestionRe: No JSON parser found PinmemberEM1L15-Jan-13 22:35 
GeneralRe: No JSON parser found PinmemberShivanand Arur15-Jan-13 22:51 
Questionit shows html Pinmemberkhinezw8-Jan-13 22:18 
SuggestionRe: it shows html PinmemberShivanand Arur9-Jan-13 19:44 
GeneralRe: it shows html Pinmemberkhinezw10-Jan-13 22:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 8 Jan 2013
Article Copyright 2013 by Shivanand Arur
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid