Click here to Skip to main content
15,883,901 members
Articles / Programming Languages / C#
Article

SignalR - Simple Chat Application in C#

Rate me:
Please Sign up or sign in to vote.
4.80/5 (54 votes)
8 Jan 2013CPOL8 min read 254.7K   20.1K   105   37
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

 Image 1

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

     Image 2

  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"

    Image 3

  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.

    Image 4

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

    Image 5

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

     Image 6

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

     Image 7

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

    Image 8

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

     Image 10

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.

C#
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

C#
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.

    Image 11

  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.

    Image 12

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

    Image 13

  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:

Image 14 

Script within the <body> tag:

Image 15 

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

Image 16

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:  

     Image 17

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

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)


Written By
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 | :)

Comments and Discussions

 
QuestionProblem Installing Microsoft.AspNET.SignalR Pin
Member 1389508214-Jul-18 6:48
Member 1389508214-Jul-18 6:48 
AnswerRe: Problem Installing Microsoft.AspNET.SignalR Pin
OriginalGriff14-Jul-18 6:51
mveOriginalGriff14-Jul-18 6:51 
QuestionError: SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started. Pin
ArJun Arora28-Jan-18 21:56
ArJun Arora28-Jan-18 21:56 
QuestionsiganlR Chat Application Pin
Member 1296929326-Jan-17 7:45
Member 1296929326-Jan-17 7:45 
QuestionCould You Please tel me how SignalR Websocket is Responsible to transfer dat ain lan network Pin
Member 125378507-Nov-16 1:54
Member 125378507-Nov-16 1:54 
QuestionReconnection problem in signalR Pin
spsornalatha24-Mar-16 1:17
spsornalatha24-Mar-16 1:17 
QuestionDoes signalr uses ipaddress and port number automatically? Pin
Member 1127985920-Jan-16 22:18
Member 1127985920-Jan-16 22:18 
QuestionGood Job! Thank you Pin
Member 1173008230-May-15 17:25
Member 1173008230-May-15 17:25 
Questionserver to server connection qusn Pin
Member 1153591018-Mar-15 4:48
Member 1153591018-Mar-15 4:48 
QuestionCan you make this into a win forms app? Pin
Member 1047794220-Feb-15 15:49
Member 1047794220-Feb-15 15:49 
Questionnot installed Pin
Member 1043461124-Dec-14 1:08
Member 1043461124-Dec-14 1:08 
QuestionGreat work !!! Pin
Amila thennakoon27-Apr-14 22:45
Amila thennakoon27-Apr-14 22:45 
GeneralMy vote of 5 Pin
Nirav Prabtani16-Apr-14 2:53
professionalNirav Prabtani16-Apr-14 2:53 
SuggestionMy vote 3 Pin
Shail Mishra14-Mar-14 1:56
Shail Mishra14-Mar-14 1:56 
GeneralMy Vote Pin
Mehdy Moini13-Dec-13 7:11
professionalMehdy Moini13-Dec-13 7:11 
QuestionNeed little guidance. Pin
VICK10-Dec-13 19:24
professional VICK10-Dec-13 19:24 
Questioninstallation problem Pin
Member 1030997924-Nov-13 16:45
Member 1030997924-Nov-13 16:45 
AnswerRe: installation problem Pin
VICK10-Dec-13 18:54
professional VICK10-Dec-13 18:54 
AnswerRe: installation problem Pin
tanywali3-Aug-14 1:44
tanywali3-Aug-14 1:44 
GeneralMy vote of 5 Pin
S.Sathik Ali2-Sep-13 21:29
S.Sathik Ali2-Sep-13 21:29 
GeneralMy vote of 5 Pin
Sampath Lokuge7-Aug-13 5:06
Sampath Lokuge7-Aug-13 5:06 
QuestionSignalR pure HTML Pin
yousefk21-Jul-13 1:52
yousefk21-Jul-13 1:52 
QuestionNice topic Pin
ADITYA SINGH RANA .10-Jun-13 4:25
ADITYA SINGH RANA .10-Jun-13 4:25 
QuestionDoubt Pin
Member 1005287415-May-13 2:53
Member 1005287415-May-13 2:53 
AnswerRe: Doubt Pin
Shivanand Arur15-May-13 3:27
Shivanand Arur15-May-13 3:27 

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

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