Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

Chat Application using ASP.NET SignalR

3.77/5 (12 votes)
22 Mar 2015CPOL7 min read 34.5K  
Chat Application using ASP.NET SignalR

ASP.NET SignalR is one of the major revolutions in the development technology world these days. Consider an application having a page where you are required to update the user interface with the latest data, as soon as it is available. Such applications are said to be real time applications, where the UI gets updated as soon as the latest data is available for the user.

Best example, a stock market application has to keep updating the user interface with the data as soon as stock rates are changed. Another example is a chat application, which updates the receiver with the latest message, from the sender. Some of the techniques could be making timer based requests to the server, for getting the data or use the concept of polling to get the data. A good alternative to these, is the use of SignalR.

As we know, our model of the web applications mainly consists of a server, which hosts the application and the client, representing the end users of the applications.For creating SignalR based applications, we need to create a hub on the server, which is responsible for updating the client or the end users with the latest data. This hub is nothing but a simple class inheriting from the Hub class. At the client end, we get an automatically generated JavaScript based proxy file (at run time), which can be used by the client for connecting with the hub. Client code also contains a JavaScript function, which the hub uses to provide them with the latest data. See the image below:

Image 1

To explain this process in detail, our hub directly calls the client JavaScript functions, to provide the latest data. On the other hand, by using the auto generated JavaScript proxy file at the client end, client code can uses this proxy, to call the methods of the server hub, if required. The term if required is used here deliberately with the fact that client may not be required to call the hub. For example, in an application where we have user dashboard with some data from database, we can use the concept of SqlDependency and SignalR to keep the user interface updated, whenever there is any change in the database records. In this case, the client is not required to make any calls to the server for getting the updates. On the other hand, if we have a chat application, the client code will call the server hub and forward the message. Hub will then broadcast this message to the users of the application, by calling JavaScript method of the clients.

One very important point from the above paragraph is that the client never calls the hub for getting the latest data. Client may only call the hub so that hub can forward the message to the other connected clients. If the client code would need to make the calls for latest data to the server, then the whole purpose of using the SignalR fails and we could have used the old concepts of timer or page refresh for this.

Simple group chat application in 15 minutes using SignalR

Yes, that's correct. Once you are aware of the basic concept/flow of SignalR, you can do it very easily. We will be now creating a group chat, without use of any database. If we think about the flow of the application, this whole process requires a client to send message to the server, which will broadcast this message to all the connected client users. So the server needs to have a component which can broadcast the message to the clients. This role is played by the hub class. This is the example, where the client needs to call the server hub. Let's try to visualize this process and then we will create the application.

 

Image 2

 

Create a new project named SignalRChat. Add the references to the SignalR libraries using nuget. It will automatically add the references to the OWIN hosting option libraries which allows to add the SignalR application to the OWIN pipeline. Apart from the server libraries, it also adds client libraries required for using SignalR. See the references get added below:

Image 3

Create OWIN Host for the Application

We will be using the OWIN based hosting, to host this application. Without going into depth of the OWIN hosting, let's add a class named Startup.cs. The name has to be the Startup as per the OWIN based hosting specifications and its namespace must be decorated with the assembly attribute, specifying that Startup assembly is the starting point of the application. Next we define a method named Configuration and register the SignalR in the OWIN pipeline using app.MapSignalR().

 

Image 4

Create the Hub on the Server

Our next step is to create the hub on the server which is nothing but a class file. We will name it as SignalRChatHub and derive from the Hub class. It will contain a method named BroadCastMessage, with 2 parameters. Client code will use this method (using the proxy generated at its end) for communication with the hub, and the parameters as the data to be sent to the hub. Inside this method, use the Clients property of the Hub class to call the client side function. This function is a simple JavaScript function, which will receive the data sent by the hub and update the chat window of the user. We will define a function with the name receiveMessage at the client end (later in the code). So for now, we will use this method name.

Image 5

A point to be noted here is that the we will not get any intellisense help for the client methods, of-course. This method will be dynamically resolved. See the image below:

Image 6

Setup the Client Code

Server setup is done. Now, we will add an HTML page named ChatWindow.html which will be our chat window for the user. Also we add the references to the jquery-1.6.4.min.js and jquery.signalR-2.2.0 .min,js on this page, which were added by the nuget package manager. Earlier we discussed that SignalR automatically generates a proxy class at run time, for client code, to connect with the hub. So we also need to reference to this file. As this file is generated at run time, it does not exist physically for us. As per the SignalR tutorials on the official ASP.NET website, it states:

"color: inherit">SignalR creates the JavaScript code for the proxy on the fly and serves it to the client 
in response to the "/signalr/hubs" URL.

So we need to add this reference also.

Image 7

We also have the option to disable this auto-generated proxy file generation (which is out of scope for this discussion) and create the proxy ourselves. In that case, we need to reference that file accordingly. Next, let's add some HTML mark-up to generate the chat window and design it using CSS styling.

Image 8

Now, it's time for client code to connect with the hub and send the message, so that hub can broadcast to all the users. For this, we first get the proxy instance in a variable named chatProxy.Note the camel case syntax of the client code below. This is the convention to be followed while creating the SignalR application. For detailed specifications, I would recommend you to check out the ASP.NET official SignalR website. Without going further into the details, let's move forward with the code. Here, signalRChatHub is the name of the hub on the server (that we created on the server earlier).

Image 9

Next, we attach the button click event (button to send message to the users), when the connection to hub is successfully started. This event will call the method of the hub, using the proxy instance, which will receive the message and broadcast it to users. See the code below:

Image 10

We also declare the function to which the hub will call, when it needs to update all the users with the message received. This is the function name we referred to, from the hub method, at the start of the discussion. So this function acts as a type of callback function here.

Image 11

So all the client code is also setup and we can now run the application. So our complete client code will now look like:

Image 12

Now, we can run the application. Copy the URL and open another instance of the browser or any other browser and we can start chatting.

Image 13

Wasn't that easy? So we have our own chat messenger. Happy coding...!!!

License

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