DCSIMG
Getting started with SignalR - Ran Wahle's blog

Ran Wahle's blog

Getting started with SignalR

Getting started with SignalR

 

Recently I’ve begun testing ASP.NET.SignalR, an open source project that supports real-time web functionality in our application.SignalR logo

SignalR can be added to an existing ASP.NET application and help as easily gain real-time functionality
in no-time. It can run with browsers that supports HTML5 WebSocket or long polling (IE 8).

 

SignalR has both server and client code, its client code is based on jQuery

In this post I’ll demonstrate how to work with SignalR along with a few basic terms related to it.

 

Install SignalR nuget package

First, you should install Microsoft.ASP.NET.SignalR nugget package, you can do so either by running install command on
nuget management console, or do so by searching the package on the nugget packages GUI.  It will install another 4 SignalR
related packages along with jQuery and JSON.Net packages which SignalR packages depends on.

 

Server Side Code

Now, what we need to do is to have some code that  will act as our service, in SignalR terms it is called Hub.
Our hub will be named SoccerResultsHub and will enable to update the home and visitor team, increment score
for each and update the time left.

For some separation of concern (even a demo needs it) here’s a class to manage hold game data

public class SoccerGame
   {
       private Timer _timer;
 
       public event EventHandler UpdateTimeLeft;
       public SoccerGame()
       {
           TimeLeft = 90;
           _timer = new Timer();
           _timer.Elapsed += (sender, args) =>
               {
                   TimeLeft--;
                   if (UpdateTimeLeft != null)
                       UpdateTimeLeft(this, null);
 
               };
           _timer.Interval = 60000;
           _timer.Start();
       }
       public string HomeTeam { get; set; }
 
       public string VisitorsTeam { get; set; }
 
       public int HomeScore { get; set; }
 
       public int VisitorScore { get; set; }
 
       public int TimeLeft { get; set; }
   }

This class will be used in our hub that looks like that:

public class SoccerResultsHub : Hub
  {
      private SoccerGame _game = new SoccerGame();
 
      public SoccerResultsHub()
      {
          _game.UpdateTimeLeft += (sender, args) => UpdateTimeLeft();
      }
 
      public void UpdateHomeTeamName(string teamName)
      {
          _game.HomeTeam = teamName;
          Clients.All.updateTeams(_game.HomeTeam, _game.VisitorsTeam);
      }
 
      public void UpdateVisitorTeamName(string teamName)
      {
          _game.VisitorsTeam = teamName;
          Clients.All.updateTeams(_game.HomeTeam, _game.VisitorsTeam);
      }
 
      public void UpdateTimeLeft()
      {
          Clients.All.updateTimeLeft(_game.TimeLeft);
      }
 
      public void ScoreForHome()
      {
          _game.HomeScore++;
          Clients.All.updateScores(_game.HomeScore, _game.VisitorScore);
      }
 
      public void ScoreForVisitors()
      {
          _game.VisitorScore++;
      }
 
 
  }
}

For each method on our Hub class, SignalR will create corresponding javascript code enables us to invoke from our client side.

Note the Clients.All.<method> , Clients property of Hub class has the connection context, and its type is self explanatory ConnectionContext .

It has several dynamic properties of which we can add method calls to, the SignalR engine will support extending its javascript ,  the All property of Clients

 

Client Side Code

On our HTML document we need to reference jQuery , SignalR base javascript library and the javascript proxy code generated by SignalR for our Hub above.

<script type="text/javascript" src="Scripts/jquery-1.6.4.js"></script>
  
 <script type="text/javascript" src="Scripts/jquery.signalR-1.0.0-alpha2.js">
</script>
 <script type="text/javascript" src="SignalR/Hubs">
</script>

We’d also use knockoutJs and that’s how our entire Html will look like:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <label for="txtHomeName">Home Team:</label>
    <input type="text" id="txtHomeName" data-bind="{value : homeTeamName}" />
    <button data-bind="{click: updateHomeTeamName}">Update</button>
    <button data-bind="{click: homeTeamScores}">Scores</button>
    <span data-bind="{text : homeTeamScore}"></span>
    <br />
     <label for="txtvisitorName">visitor Team:</label>
    <input type="text" id="txtvisitorName" data-bind="{value : visitorTeamName}" />
     <button data-bind="{click: updateVisitorTeamName}">Update</button>
    <button data-bind="{click: visitorTeamScores}">Scores</button>
    <span data-bind="{text : visitorTeamScore}"></span>
    <br />
    <span>Time Left:</span>
    <span data-bind="{text : timeLeft}"></span>
    <script type="text/javascript" src="Scripts/knockout-2.2.0.js"></script>
     
      <script type="text/javascript" src="Scripts/jquery-1.6.4.js">
    </script>
   <script type="text/javascript" src="Scripts/jquery.signalR-1.0.0-alpha2.js">
   </script>
       <script type="text/javascript" src="SignalR/Hubs">
    </script>
       <script type="text/javascript" src="GameViewModel.js">
</script>
</body>
</html>

 

Using knockoutJs  lets us have our client code deals with the data itself and doesn’t involve any DOM manipulation

In our javascript code we declare a view-model and inside it declare a member named gameHub. This member will be declared as the Hub connection
to the server. it will use to start the connection, call server methods and extend the client so the server can call functions on it (it is bi-directional right?)

You can see that gameHub member has client and server  members used for both purposes mentioned above

That’s how our javascript code will look like:

 
var viewModel =
    {
        gameHub : null,
        homeTeamName: ko.observable(),
        homeTeamScore: ko.observable(),
        visitorTeamName: ko.observable(),
        visitorTeamScore: ko.observable(),
        timeLeft: ko.observable(),
        homeTeamScores : function()
        {
            this.gameHub.server.scoreForHome();
        },
        visitorTeamScores: function () {
            this.gameHub.server.scoreForVisitors();
        },
        updateScores: function (home, visitors) {
            this.homeTeamScore(home);
            this.visitorTeamScore(visitors);
        },
            updateHomeTeamName : function()
            {
                this.gameHub.server.updateHomeTeamName(this.homeTeamName());
            },
            updateVisitorTeamName: function () {
                this.gameHub.server.updateVisitorTeamName(this.visitorTeamName());
            }
    };
 
$(document).ready(function () {
    
    ko.applyBindings(viewModel);
 
    viewModel.gameHub = $.connection.soccerResultsHub;
    viewModel.gameHub.connection.start();
 
    $.extend(viewModel.gameHub.client,
        {
            updateTimeLeft: function (timeLeft) {
                viewModel.timeLeft(timeLeft);
            },
            updateTeams: function (home, visitors) {
                viewModel.homeTeamName(home);
                viewModel.visitorTeamName(visitors);
            },
            updateScores: function (home, visitors) {
                viewModel.updateScores(home, visitors);
            }
        });
});

 

Summary

SignalR let’s us have bi-directional communication between the client and server. It runs on browsers that support websockets and long-polling

while signalR knows which of those features to use. It depends on jQuery on client side and Newtonsoft.Json (and ASP.NET) on server side.

It is still in alpha stage but sure worth a try,  knowing how to use it will help you create great Http based applications.

 

The entire sample can be downloaded here.

kick it on DotNetKicks.com

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# December 11, 2012 5:17 PM

Ran Wahle's blog said:

Using SignalR with .Net client &#160; In my previous post I demonstrated how to use SignalR with javascript

# December 29, 2012 2:16 PM

Ran Wahle's blog said:

Self Hosting SignalR SignalR , as shown in the earlier posts, can be hosted within a regular ASP.NET

# January 20, 2013 5:59 AM

Irvin said:

Touche. Solid arguments. Keep up the great effort.

# January 20, 2013 6:45 PM

Ran Wahle's blog said:

SignalR Protocol &#160; After showing how to get started with SignalR , how to use it with .Net client

# February 17, 2013 3:24 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: