WebSocket Using SignalR

imageSignalR offers a simple and clean API to write real time web applications where the server needs to continuously push data to clients. Common applications are chat, news feed, notifications, multiplayer games.

SignalR will use WebSockets under the covers when it’s available, and gracefully fallback to other techniques and technologies when it isn’t, while your application code stays the same.

When to Use SignalR

SignalR can be used to add any sort of “real-time” web functionality to your ASP.NET application. While chat is often used as an example, you can do a whole lot more. Any time a user refreshes a web page to see new data, or the page implements Ajax long polling to retrieve new data, is candidate for using SignalR.

SignalR simplifies the process of building real-time applications. It includes an ASP.NET server library and a JavaScript client library to make it easier to manage client-server connections and push content updates to clients. You can add the SignalR library to an existing ASP.NET application to gain real-time functionality.

SignalR is an open-source .NET library.

Getting SignalR

SignalR is available on NuGet in libraries and as a sample that will load directly into your app.

It is also available on GitHub.

Check out the SignalR site.

You will need:

Microsoft ASP.NET and Web Tools 2012.2. For Visual Studio 2012, this installer adds new ASP.NET features including SignalR templates to Visual Studio. For Visual Studio 2010 SP1, an installer is not available but you can complete the tutorial by installing the SignalR NuGet package as described in the setup steps.

Setting Up the Project

First, create an ASP.NET Empty Web Application.

Create empty web

Next, In Solution Explorer, right-click the project, select Add | New Item, and select the SignalR Hub Class item. Name the class ChatHub.cs and add it to the project. This step creates the ChatHub class and adds to the project a set of script files and assembly references that support SignalR.

Add SignalR Hub class

Replace the code in the new ChatHub class with the following code.


using System;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalRChat
{
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
}
}

The Send method demonstrates several hub concepts :

  • Declare public methods on a hub so that clients can call them.
  • Use the Microsoft.AspNet.SignalR.Hub.Clients dynamic property to access all clients connected to this hub.
  • Call a jQuery function on the client (such as the broadcastMessage function) to update clients.

Next, you will start up the server in the Global.asax file. In Solution Explorer, right-click the project, then click Add | New Item. In the Add New Item dialog, select Global Application Class and click Add.


using System;
using System.Web.Routing;
namespace SignalR
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
// Register the default hubs route: ~/signalr/hubs
RouteTable.Routes.MapHubs();
}
// .. other Application_ methods
}
}

Routes are URL patterns that are used for processing requests and that can be used to construct URLs dynamically. The Routes property is a static property (Shared in Visual Basic) that represents all the objects that are used to specify how a URL request is matched to a class that handles the request.

When an ASP.NET application handles a request, the application iterates through the collection of routes in the Routes property to find the route that matches the format of the URL request. The order of the routes that you add to the Routes property is significant, because the application uses the first route in the collection that matches the URL.

Creating the Client

In Solution Explorer, right-click the project, then click Add | New Item. In the Add New Item dialog, select Html Page and click Add.

Set the page as Start Page, then replace the HTML  with the following code.


<!DOCTYPE html>
<html>
<head>
<title>SignalR Simple Chat</title>
<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;
}
</style>
</head>
<body>
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
<!–Script references. –>
<!– Reference the jQuery library. –>
<script src="/Scripts/jquery-1.8.2.min.js" ></script>
<!– Reference the SignalR library. –>
<script src="/Scripts/jquery.signalR-1.0.0.js"></script>
<!– Reference the autogenerated SignalR hub script. –>
<script src="/signalr/hubs"></script>
<!– Add script to update the page and send messages. –>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
</body>
</html>

Some notes:

var chat = $.connection.chatHub;  In jQuery the reference to the server class and its members is in camel case. The code sample references the C# ChatHub class in jQuery as chatHub.

The following code shows how to open a connection with the hub. The code starts the connection and then passes it a function to handle the click event on the Send button in the HTML page.


$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});

Run You Chat App

When you run the page, you will need to log in with a user name.

Enter user name

Start up several more users by copying the address line in the browser, and add in a unique user name.

The hub broadcasts comments to all current users. Users who join the chat later will see messages added from the time they join.

Inspect the hubs file

In Solution Explorer, inspect the Script Documents node for the running application. There is a script file named hubs that the SignalR library dynamically generates at runtime. This file manages the communication between jQuery script and server-side code.

Generated hub script

Resources