SignalR Online Counter Sample


SignalR is a web technology for building real time ASP.NET web applications. SignalR is an open source project which simplifies the complicated tasks of creating bidirectional communication between clients and server. SignalR is founded on top of WebSockets, as well as other similar technologies.

As you probably know WebSockets introduced a new way to communicate between server and clients, and it is specified by the HTML5 API specification. When it is available SignalR will use this technology, otherwise it will use what is supported by your system. SignalR also provides a high-level API for server communication to client RPC (call JavaScript functions in clients’ browsers from server-side .NET code) in ASP.NET applications, as well as adds useful hooks for connection management, e.g., connect/disconnect events, grouping connections, authorization. More information about SignalR can be found on the official web site for SignalR.

For this post I have implemented a very simple SignalR Web Application which counts how many users are online, so it is called Online Counter. Online Counters are a very popular component for the web.

So let’s start with the implementation.

  1. Open Visual Studio 2012, and create new Empty Web Application called OnlineCounter.

SignalR_image1

The first thing we will do is adding SignalR reference for the clients (JavaScript files) and the Server (.NET Components).

2. So open NuGet Manager console and input the following command: Install-Package Microsoft.AspNet.SignalR –Pre

SignalR_image2

After we added SignalR references, we are implementing Server side of the SignalR HitCounter Web Application.

3. Add a new class named HitCounter.

SignalR_image3

The HitCounter class must be derived from the Hub. More info about Hub and other SignalR components you can find on the official site.

The implementation for the HitCounter class is shown below:

public class HitCounter : Hub
{

 private static int clientCounter = 0;

 public void Send()
 {
 string message = "";
 // Call the recalculateOnlineUsers method to update clients
 if(clientCounter<2)
 message = string.Format("Currently {0} user is online.",clientCounter);
 else
 message = string.Format("Currently {0} users are online.", clientCounter);

 Clients.All.recalculateOnlineUsers(message);
 }

 ///
/// register online user
 ///
 ///
 public override System.Threading.Tasks.Task OnConnected()
 {
 clientCounter++;
 return base.OnConnected();
 }

 ///
/// unregister disconected user
 ///
 ///
 public override System.Threading.Tasks.Task OnDisconnected()
 {
 clientCounter--;
 return base.OnDisconnected();
 }
}

As you can see from the source code, we have override two virtual methods when user is reach the page, and also when the user live the page. The Send method is responsible to send message to all available clients.

We need also to implement Global Application Class to register this hub.

4. Add Global Application Class in to your project, and register MapHubs, as picture shows below.

SignalR_image4

The following code implementation shows how to register Hub in Global App Class.

public class Global : System.Web.HttpApplication
{

    protected void Application_Start(object sender, EventArgs e)
    {
        // Register the default hubs route: ~/signalr/hubs
        RouteTable.Routes.MapHubs();
    }
//rest of the implememtation.....

After we implemented Services side of SignalR, we need to implement client side.

5. Add new html web page in to project.

SignalR_image6

6. Include standard set of JavaScript files necessary for SignalR client to run.

<!--Script references. -->
<!--Reference the jQuery library. -->
<script type="text/javascript" src="Scripts/jquery-1.6.4.min.js"></script><!--Reference the SignalR library. --><script type="text/javascript" src="Scripts/jquery.signalR-1.0.0-rc2.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script type="text/javascript" src="/signalr/hubs"></script>

7. Send Notification to Server that the new User is reached the page.
8. Implemet JavaScript code to receive recalculateOnlineUser event sent from server.

    $(function () {

        // Declare a proxy to reference the hub.
        var counter = $.connection.hitCounter;

        // register online user at the very begining of the page
        $.connection.hub.start().done(function () {
            // Call the Send method on the hub.
            counter.server.send();
        });

        // Create a function that the hub can call to recalculate online users.
        counter.client.recalculateOnlineUsers = function (message) {

            // Add the message to the page.
            $('paragraph').text(message);
        };

    });

9. Compile and run the code. Open two Browser Windows. You can see that SignalR has counted two online users.

SignalR_image7

Source code for this blog post demo you can find below.

About these ads

About Bahrudin Hrnjica

Senior Software Developer at daenet, Microsoft MVP for C#. Likes C , WPF, Silverlight, WP7, Math, Mechanical Engineering, Evolutionary Algorithms, Blogger.

Posted on 28/01/2013, in .NET, C#, CodeProject and tagged , , , . Bookmark the permalink. 6 Comments.

  1. Excellent article. Enjoyed reading it. I would just like to know whether there is any disadvantage in using the signalr?

    • Thanks for the comment.
      Permanent connection between server and clients is one of disadvantage. The second: If servers are in cluster, I dont know will SignalR send message to clients which are not on the same server within one cluster.
      Hope you satisfied with answer.

  2. Could just be me, but the downloaded source code works fine when new clients are connected, but on disconnection the send function is not triggered and therefore the displayed number of clients is incorrect

  3. Hi Bahrudin, good article, you permit me translate to spanish in my blog.

  1. Pingback: SignalR Online Counter Sample - C# & .NET technologies - developers.de

Leave a Reply

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

Follow

Get every new post delivered to your Inbox.

Join 549 other followers