Using SignalR – Basic Chat Application

After introducing you to SignalR in my previous post, I thought it was time I showed you how to use SignalR with a basic SignalR tutorial. In this tutorial I will be running through creating a basic chat application with SignalR and Visual Studio 2012. Our application will be very simple, and focus on just have one chat box, with the ability for users to register a username, and send messages to the chat box.

A Basic Chat Application

The code for the following tutorial can be downloaded here: Download SignalR Chat Application Source

First we start by creating a new project in Visual Studio. Select the MVC4 template, and then I started mine from the Basic template, though certainly feel free to build your own solution from the Empty template (you will have to create a bundle config file, shared layout etc).

Select the MVC4 Basic Template

Once the MVC4 application has been created, next we need to add the Index page. Create a folder called “Home” under the Views folder and add a view to it called Index. Then create a controller in the controller folder called “HomeController”. This should already contain an Index() method that returns the View. Now if you are to run your application, it should work, and we should see that the Index Page is rendered inside the Shared Layout (The _Layout.cshtml file in /Views/Shared). You should also see that certain bundles are rendered.

Now we need to move on to adding SignalR to our application. SignalR has a nuget package that will handle all the required files for us. Add the SignalR nuget package to the solution. You can do this by selecting to search online, and searching for SignalR. Then make sure you add the entire SignalR package (and not just one of the clients, see image below).

Adding the SignalR Nuget Package

To allow for support in older browsers, also add the “JSON2” nuget package (This enables JSON support in older browsers, see the github page for more information).

We need a little bit more configuration to include SignalR in our application. First lets setup the bundle to include the required JavaScript files. Open the BundleConfig.cs file in the App_Start folder, and add the following line anywhere in the RegisterBundles method:

This adds a bundle we can add to our page for SignalR that includes both the SignalR file, and the json2 file.

We also need to register the default route for the SignalR hubs. The hubs are what do our server side work in SignalR, and our application needs to know where to find them. Fortunately SignalR adds an extension method to make this easy. All we need to do is add the following line to our Global.asax file, just after we register all areas:

Your Application_Start() method should look like the following after this has been done:

Now we need to start designing our actual chat page. We first need to include our scripts on the page. jQuery was included in the shared layout so we don’t need to worry about that, but it is a requirement for SignalR. Our shared layout did give us a section for scripts so we might as well make use of this. To do so, add the following to our Index View:

The first line renders the SignalR bundle we set up, the second can only be called after the SignalR JavaScript file is included, as the file doesn’t exist, it’s auto generated by the SignalR JavaScript file.

Now we want to add our chat display. For this I’ve used bootstrap to simplify the styling. First of all, search for and add the bootstrap nuget package. Once this is installed, you will need to add in bundles for the style and the script. I added the css to the overall css bundles (“~/Content/css”) before the site.css file, and created a separate bootstrap bundle for the script. Finally add the new bundles to the shared layout.

Now to move onto the markup. Add the following to the Index.cshtml file, just below the <h2> tag:

This is simple, it gives us an input for the username, an input to display messages, and an input to send a message, with a button to submit the form. Most of the classes are bootstrap classes, and we have a class to hide various elements, to allow us to only show what we want to the user at any particular point. If you want you can also change the title of the page to something more appropriate rather than Index. You will need to add the following to the “site.css” file found in the Content folder:

This at the moment won’t look very pretty. You’ll just have a loading message. We’ll need to add the functionality in with JavaScript. This is where the magic of SignalR occurs. SignalR allows us to call messages from client side, or server side, directly from JavaScript, and C#.

First we need to create our SignalR Hub. Add a folder called Hubs to your project, and in it, add a new class called ChatHub. All SignalR Hubs are simply C# classes, that inherit from the Hub class. Our Hub is going to be very simple. The Code is below:

There is a bit to talk about here. You can see the class inherits from Hub. It also has an annotation giving it a HubName. This just means we can refer to the hub by the name given here.

We have three methods in the class, but really we are performing two functions here, either connecting users, or sending messages. We have created a static dictionary that contains all the usernames against the connection ids. SignalR conveniently assigns each connection a unique id that we can identify each user by.

Our ConnectUser method takes a username, and checks that we don’t already have someone with the same username connected (by checking it doesn’t match any in the dictionary). If it doesn’t we add the username to the dictionary with a key of the connection ID. Finally we return true if we added the user and false otherwise.

Our SendMessage method takes a string for the message, checks whether there is a reference for the user in the ConnectedUsers (this shouldn’t be a problem, but it’s to prevent errors), and then sends a message to all the other users connected.

SignalR provides us with some useful things here. As mentioned, we can fetch the Context of the current user, and on this get the id of the current connection by the  Context.ConnectionId call. This allows us to identify which user called the method. Also as SignalR is aware of which client made the method call, we can use the  Clients.Others to call a method on all the other clients apart from the one which called the method. This is often preferable. For example, when sending a message, the client that sent the message knows the user, and the message, so it needs nothing from the server. We can save some effort by handling it client side for that client, and letting the server push it out to the rest of the connected clients.

The other part of the hub is overriding the OnDisconnected method. SignalR is aware when a user leaves, and we can handle the event. Here it is important to do so, so we remove the user from are ConnectedUsers list, so that’s exactly what we do in this method.

Now we have the server side set up for our application’s real time events, we just need to action this from the client side.

First we need to add a script tag to the end of the scripts section on our Index View. Inside of here include a self executing anonymous function to prevent our variables being in the global namespace. Next we add two variables that we would use, one for our hub, and for the the username. It should look like the following:

We can connect to our hub by accessing it by the name we gave it on the $.connection object SignalR provides us. This is assigned to a variable to cache it.

Next we need to start our connection to the hub. SignalR uses jQuery’s promises system, so all the functions are asynchronous, and we can use .done() to provide a callback for when the method finishes executing. We can use this to attach our click events and manipulate the display when are connection is established to allow the user to use are chat application once we are connected.

First we will produce an init method to hide the loading message, and display our chatbox:

We then connect to the hub, calling the init method once connected:

You can see starting the connection is simple, and we provide a callback function to be executed once we are connected. The function inside the .done() is only executed once we are connected. We will add a couple of event handlers in here later as well, as it is best to only hook up the events that require connection to the hub, after we have connected, to prevent the user triggering the events before we can handle them.

We first require our user to add a username to connect. The following function is required for handling when the user connects to switch to the main chat box.

We then have to add in an event to handle the user submitting a username. Add the following inside the .done() function, after the init() call:

The key thing to notice here is how we call our method on the server. We use our variable we assigned to our chatHub, and explictly tell it we are calling a method on the server with the .server, then call the method name. Notice how we named the ConnectUser method on the server with an uppercase, but call it with lowercase in JavaScript, as this is JavaScript convention. SignalR is fine with this. We are actually calling the server side method like this, and passing it a variable. The function also has a return value which we handle in our .done() function with the connected variable. The rest of the code should be fairly obvious it’s purpose.

So finally we have reached our actual chat box. If you were to run the solution now, you would see an example of talking to the server and receiving a response with the username. and if you used two different browsers you would see you could not use the same username in both sessions.

Our chat function is very simple. First we add our display message function:

The function itself does nothing fancy. It takes a username, and a message, and creates an element to add this to our chat display, and finally scrolls to the bottom of the chat display. The interesting bit is the last line. This hooks up our function to the SignalR hub and allows us to call this method from the server. We simply set the name we want to use for the method equal to the function. Now our server side code can call the displayMessage function.

Finally add the event handler to the code just after the username form event handler:

This hooks up submitting the chat form. The final thing you may want to do is just add the following to the css to display the usernames in bold in the chat box:

So there you have a basic chat application. There is plenty you can do, such as display the list of connected users on each client, store some of the chat history so when users connect they can see what the talk has been about, and even create separate rooms by exploring the option to add connections to groups in SignalR and send messages to specific groups.

You can download the code from this example here: Download SignalR Chat Application Source

4 thoughts on “Using SignalR – Basic Chat Application

    • This would just be a case of writing the code like you usually do, but doing this inside your method in the signalr hub. It is just normal c# code on the server side.

Leave a Reply