SignalR - Simple Chat Application in C#
Hello friends, today I am going to explain to you how to create a simple chat application using SignalR.
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.
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".
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 :
- C# Class file â€“ "LetsChat.cs"
- Web Form â€“ "Chat.aspx"
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.
public class Global : System.Web.HttpApplication
protected void Application_Start(object sender, EventArgs e)
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
public class LetsChat : Hub
public void send(string 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:
- Clients.All - This represents all the Clients, so whenever a message is sent, then that message is received by all the connected clients.
- 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.
- Clients.Others - Here other than the Caller, the message will be posted to all the connected clients.
- 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:
- 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;"
- 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.
- 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.
- 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:
- 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:
- In this image, I have written a message in Google Chrome and is displayed on IE at the same time.
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.