Click here to Skip to main content
15,125,746 members
Articles / Programming Languages / Javascript
Technical Blog
Posted 29 Jan 2013

Stats

41.1K views
20 bookmarked

SignalR Online Counter Sample

Rate me:
Please Sign up or sign in to vote.
4.25/5 (5 votes)
22 Apr 2013CPOL2 min read
A very simple SignalR Web Application which counts how many users are online.

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:

C#
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 the Global App class.

C#
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.

XML
<!--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.

JavaScript
$(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.

Source code link.

This article was originally posted at http://bhrnjica.net/2013/01/28/signalr-hit-counter-sample

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Bahrudin Hrnjica
Software Developer (Senior)
Bosnia and Herzegovina Bosnia and Herzegovina
Bahrudin Hrnjica holds a Ph.D. degree in Technical Science/Engineering from University in Bihać.
Besides teaching at University, he is in the software industry for more than two decades, focusing on development technologies e.g. .NET, Visual Studio, Desktop/Web/Cloud solutions.

He works on the development and application of different ML algorithms. In the development of ML-oriented solutions and modeling, he has more than 10 years of experience. His field of interest is also the development of predictive models with the ML.NET and Keras, but also actively develop two ML-based .NET open source projects: GPdotNET-genetic programming tool and ANNdotNET - deep learning tool on .NET platform. He works in multidisciplinary teams with the mission of optimizing and selecting the ML algorithms to build ML models.

He is the author of several books, and many online articles, writes a blog at http://bhrnjica.net, regularly holds lectures at local and regional conferences, User groups and Code Camp gatherings, and is also the founder of the Bihac Developer Meetup Group. Microsoft recognizes his work and awarded him with the prestigious Microsoft MVP title for the first time in 2011, which he still holds today.

Comments and Discussions

 
Questiontanks Pin
babak354810-Dec-13 1:44
Memberbabak354810-Dec-13 1:44 
Questiondesign flaws Pin
Vahid_N28-Nov-13 1:06
MemberVahid_N28-Nov-13 1:06 
QuestionError when running in IIS rather than IIS Express Pin
Member 103267949-Oct-13 18:34
MemberMember 103267949-Oct-13 18:34 
QuestionSignalR Deployment Problem Pin
simanchal@gmx.com24-Sep-13 23:19
Membersimanchal@gmx.com24-Sep-13 23:19 
QuestionJavaScript runtime error Pin
Mo Kash3-Jun-13 0:49
MemberMo Kash3-Jun-13 0:49 
AnswerRe: JavaScript runtime error Pin
Bahrudin Hrnjica4-Jul-13 21:06
professionalBahrudin Hrnjica4-Jul-13 21:06 
Hi,

thanx for comment. Regarding you question could be that the browser mode is old. So press F12 and check you browser and document mode.
QuestionI like this article! Pin
Mo Kash31-May-13 2:53
MemberMo Kash31-May-13 2:53 
GeneralMy vote of 4 Pin
Mo Kash31-May-13 2:48
MemberMo Kash31-May-13 2:48 
QuestionRegarding hub url for autogenerated code Pin
Tridip Bhattacharjee22-Apr-13 4:41
professionalTridip Bhattacharjee22-Apr-13 4:41 
AnswerRe: Regarding hub url for autogenerated code Pin
Bahrudin Hrnjica22-Apr-13 23:24
professionalBahrudin Hrnjica22-Apr-13 23:24 
GeneralMy vote of 5 Pin
Member 43208448-Feb-13 7:42
MemberMember 43208448-Feb-13 7:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.