C# Corner

Building Web Apps with SignalR, Part 1

In the first installment of app-building with SignalR, learn how to build a real-time chat application.

More on this topic:

Are you sick of that dreaded page refresh? Want to turn your Web application up to 11? If you've answered yes to either question, SignalR is for you. With SignalR, you can provide content to your users in real-time, all from ASP.NET. Most importantly, it's compatible with browsers ranging all the way back to IE6! SignalR uses WebSockets on supported browsers and will fall back to server-side events, Forever Frame, or AJAX long polling if needed. This means you can use a single library and not have to worry about that minutia.

There are two approaches you can use with SignalR to achieve real-time communications: a persistent connection or a hub. The persistent connection API allows you to keep open a persistent connection between the client and server to send and receive data. The hub API is an abstraction above the persistent connection API, and is suitable for remote procedure calls (RPC).

This article will focus on the persistent connection API. I believe the best way to learn a new technology is to build something useful with it, so we'll create a chat client using SignalR. To get started, create a new C# ASP.NET MVC 4 project from Visual Studio 2012, then select the Web API option for your project type. Next, install the Microsft SignalR pre-release NuGet package through the NuGet Package Manager (Figure 1).


[Click on image for larger view.]
Figure 1. Installing the SignalR pre-release NuGet package.

In order to support IE 6 and 7, install the JSON-js-json2 NuGet Package as well, as shown in Figure 2.


[Click on image for larger view.]
Figure 2. JSON2 NuGet package installation.

Without further ado, let's get started on this app. First create a new folder in the project named Chat. Then create a new class named ChatConnection within the Chat directory that inherits from PersistentConnection. You'll need to add a using statement for the Microsoft.AspNet.SignalR namespace.

Now open up the RouteConfig class under the App_Start folder in the project. Add a using statement for the Microsoft.Asp.Net.Signal namespace to the RouteConfig class:

using Microsoft.AspNet.SignalR;

Next, register the ChatConnection class to the "chat" route in the RegisterRoutes method in the RouteConfig class:

RouteTable.Routes.MapConnection<ChatConnection>("chat","chat/{*operation}");

Your completed RouteConfig class should resemble Listing 1.

Now to create the ChatData data structure that will be used to interchange data between the client and the server. Create a new class named ChatData with Message and Name string data type properties:

namespace VSMSignalRSample.Chat
{
    public class ChatData
    {
        public string Name { get; set; }
        public string Message { get; set; }

        public ChatData()
        {
        }

        public ChatData(string name, string message)
        {
            Name = name;
            Message = message;
        }
    }
}

Now it's time to finish implementing the ChatConnection class, which will receive and broadcast chat messages. Add using statements for the System.Threading.Tasks and Newtonsoft.Json namespaces. Next, add a private Dictionary<string, string> to store the clients that connect to the chat room:

private Dictionary<string, string> _clients = new Dictionary<string, string>();

The PersistentConnection base class includes functionality for dealing asynchronously with a few critical server-side events such as a new connection, disconnection, reconnection and data retrieval. Let's implement the OnConnectedAsync event handler first. When a new user first joins the room, they're added to the _clients Dictionary object, which will be used to map the user's chosen chat name with their connectionId. Then a broadcast message is sent to all users, letting them know a new user has joined the chat room:

protected override Task OnConnectedAsync(IRequest request, string connectionId)
{
    _clients.Add(connectionId, string.Empty);
    ChatData chatData = new ChatData("Server", "A new user has joined the room.");
    return Connection.Broadcast(chatData);
}

Now it's time to tackle data retrieval from a connected client through the OnReceivedAsync event handler. First, the JSON data object from the client is desterilized into a ChatData object through JSON.NET. Then the user's name is stored in the _clients dictionary. Finally, the user's ChatData is broadcast to all users:

protected override Task OnReceivedAsync(IRequest request, string connectionId, string data)
{
    ChatData chatData = JsonConvert.DeserializeObject<ChatData>(data);
    _clients[connectionId] = chatData.Name;
    return Connection.Broadcast(chatData);
}

The last event to handle is client disconnection, via the OnDisconnectedAsync method. When a user disconnects, he or she is removed from the _clients dictionary. Then a message is broadcast to all users, letting them know a user has left the room:

protected override Task OnDisconnectAsync(IRequest request, string connectionId)
{
    string name = _clients[connectionId];
    ChatData chatData = new ChatData("Server", string.Format("{0} has left the room.", name));
    _clients.Remove(connectionId);
    return Connection.Broadcast(chatData);
}

Now it's time to create the client-side JavaScript that will communicate with the persistent chat connection to display incoming chat messages and chat room events to the user. Create a new JavaScript file named ChatR.js within the Scripts folder. The first step is to retrieve the server chat connection object through the SignalR JavaScript plug-in:

var myConnection = $.connection("/chat");

Next, the received event is set up to display a received chat message as a new list item element in the messages unordered list DOM element:

myConnection.received(function (data) {
        $("#messages").append("<li>" + data.Name + ': ' + data.Message + "</li>");
    });

After that, the error handler for the connection is set up to display a console warning. This is mainly to ease debugging of the chat connection:

myConnection.error(function (error) {
        console.warn(error);
    });

Lastly, a connection is initiated to the chat server and a continuation is set up to handle the message send button-click event. Within the button-click event handler, the user's name and message are retrieved from the name and message text boxes, respectively. Then the user's name and message are sent to the chat server as a JSON object, as shown in Listing 2.

Now it's time to set up the UI for the Web application. Add a new MVC View class to the Home directory, named ChatR, that binds to the Chat.ChatData model. In the bottom of the view add a script reference to the ~/Sciprts/ChatR.js script created earlier:

@{
    ViewBag.Title = "Chat";
}

<h2>Chat</h2>

@using (Html.BeginForm()) {
    @Html.EditorForModel();

<input id="send" value="send" type="button" />
<ul id="messages" style="list-style:none;"></ul>
}   
    
@section Scripts { <script src="~/Scripts/ChatR.js"></script> }

Now, add a controller action method named ChatR to the HomeController that returns a new view bound to an empty Chat.ChatData object:

public ActionResult ChatR()
 {
     var vm = new Chat.ChatData();
     return View(vm);
 }

That's it: sit back, relax and invite a few friends to try out your new chat app, shown in Figure 3.


[Click on image for larger view.]
Figure 3. The completed real-time chat application.

As you can, see SignalR is quite easy to work with and the PersistentConnection API is very flexible. With SignalR, you can tackle a plethora of real-time Web app use cases from business to gaming. Stay tuned for the next installment, which covers how to use the SignalR Hub API to create a dynamic form.

More on this topic:

About the Author

Eric Vogel is a Sr. Software Developer at Kunz, Leigh, & Associates in Okemos, MI. He is the president of the Greater Lansing User Group for .NET. Eric enjoys learning about software architecture and craftsmanship, and is always looking for ways to create more robust and testable applications. Contact him at vogelvision@gmail.com.

comments powered by Disqus

Reader Comments:

Fri, Feb 22, 2013 Eric Tan Singapore

Dear all, its ok. I gave up trying to resolve the issue. In the end, i created a totally new project and wrote my own code and it works! I just dont get it why it is not working by following the exact same steps as this sample though. Anyway thanks all!

Fri, Feb 8, 2013 Craig

Anyone else see/solve the 404 Eric Tan mentions? Only happens after upgrade to SignalR RC2

Fri, Feb 8, 2013 Ahmedalbarakani yemen

good

Fri, Feb 8, 2013 furkan www.kardelennakis.blogspot.com

Very good thinking.Thanks.

Wed, Feb 6, 2013 Keith Ward

Dominik, we fixed the problem with Listings 1 and 2. Thanks for spotting that!

Wed, Feb 6, 2013 d d

d

Tue, Feb 5, 2013 Eric Tan Singapore

Dear Eric, Your article is great and your sample app works! I tried to do the exact same steps but i was unable to chat with the following error encountered. NetworkError: 404 Not Found - http://localhost:49385/chat/negotiate?_=1360112765490 The Nuget package for signalr has been upgrade to RC2 recently. Are you able to advise on my error? Thanks!

Sat, Feb 2, 2013 Dominik

First of all, thanks for the tuorial. A few notes: -You mixed up Listing 1 and Listing 2 in the text, Listing 1 shows the js file, not the RouteConfig. -"First, the JSON data object from the client is desterilized into a ChatData object" -> probably should read "deserialized" ;) -SignalR change the method names of PersistentConnection lately, they now lack the "Async" suffix. (e.g. OnConnected instead of OnConnectedAsync) Anyway, keep up the good work!

Fri, Jan 25, 2013 Eric Vogel Okemos, MI

G, the next article in the series demonstrates how to create a real-time CRUD app. Scott, you can create a group with the two needed members to create a 1-1 chat.

Fri, Jan 25, 2013

Dear Eric, Would you kindly give an example of a CRUD web app and a database? Thank you G.

Fri, Jan 25, 2013 Scott

Good article Eric. What would your recommendation be if you wanted to create a website chat for 1-to-1 communication (like LiveChat)?

Add Your Comments Now:

Your Name:(optional)
Your Email:(optional)
Your Location:(optional)
Comment:
Please type the letters/numbers you see above

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.