Chat application using ASP.Net Signal R


ASP.Net SignalR is one of the major revolution in the development technology world these days for creating real time applications. 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 now that 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 latest data. See the image below:

Chat application using SignalR

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 than 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, than 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 the 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 than we will create the application.

SignalRChat_13

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

Chat application using SignalR

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().

Chat application using SignalR

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.

Chat application using SignalR

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:

Chat application using SignalR

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 pagewhich were added by the nuget package managerEarlier 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:

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.

Chat application using SignalR

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.

Chat application using SignalR

Now its 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).

Chat application using SignalRNext, 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 be receive the message and broadcast it to users. See the code below:

Chat application using SignalR

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.

Chat application using SignalR

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

Chat application using SignalR

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.

Chat application using SignalR

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

Advertisements

About Jasminder

.Net developer and blogger by profession, keen to learn new technologies, love nature, music and cricket.
This entry was posted in advanced concepts & industry trends, SignalR and tagged . Bookmark the permalink.

I have a suggestion..

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s