Creating a Simple Live Cricket Score Using ASP.NET SignalR
Join the DZone community and get the full member experience.
Join For FreeIntroduction:
I am from Pakistan. Like most of Pakistanis, I am also a huge fan of Cricket. Yesterday, I got some time from my busy job. I thought to create a simple Cricket Live Score feature using ASP.NET SignalR. It is also Interesting to note that the guys(David Fowler from West Indies and Damian Edwards from Australia) that are heavily involved in SignalR development are also cricket fans(correct me if I am wrong). In this article, I will show you how to create a simple 'Live Cricket Score' feature using SignalR. For a quick demo, just open this link in different browsers and in one browser just append ?admin= query-string(which will become the admin who update the score), then just click Update Score button many times until 2 overs finish(the match will be limited to 2 overs). For each click, the live score will be updated in each browser.
Description:
If you are new to SignalR then Getting Started will be great for you. Assuming that you have configured your application with ASP.NET SignalR. Let create a simple html page with following lines,
<!DOCTYPE html> <html> <head> <title>Pakistan v/s India</title> <style> .team { font-size: 15px; padding-right: 10px; font-weight: bold; text-transform: capitalize; } .wickets,overs { padding-right: 5px; } </style> </head> <body> <h1>Pakistan v/s India</h1> <div id="updateScore" style="display: none;"> <input type="button" id="updateScoreLink" value="Update Score"/> </div> <br /> <div data-bind="foreach: teams"> <div> <span class="team" data-bind="{ html: team }"></span> <span class="runs" data-bind="{ html: runs }"></span>/<span class="wickets" data-bind="{ html: wickets }"></span> <b>Overs</b> <span class="overs" data-bind="{ html: oversText }"></span> </div> </div> <script src="Scripts/jquery-1.8.2.min.js" ></script> <script src="Scripts/jquery.signalR-1.0.1.min.js"></script> <script src="signalr/hubs"></script> <script src="Scripts/knockout-2.2.0.js" ></script> <script type="text/javascript"> // Here we start </script> </body> </html>
In the above page, we have referenced jquery, signalr and knockout scripts. We have also define a simple template which will show the runs, wickets and overs of both teams. For demo purpose, we have added a Update Score button in the page. This button when clicked will record a single ball of an over as well as runs scored in this ball . After each ball, I will tell SignalR to broadcast teams score-card across all the connected client. When the match finished(after 24 balls), I will again tell the SignalR to show the final result to all users. Here are the scripts which are required for our work,
$(function () { var chat = $.connection.cricketHub, viewModel = { teams: ko.observableArray([ { team: 'india', runs: 0, wickets: 0, balls: 0, oversText: '0.0' }, { team: 'pakistan', runs: 0, wickets: 0, balls: 0, oversText: '0.0'}]) }, index = 0;// index represant the position of the current batting team chat.client.updateScore = function (t) { viewModel.teams(JSON.parse(t)); }; chat.client.matchFinished = function (result) { alert(result); }; $.connection.hub.start().done(function () { $('#updateScoreLink').click(function () { var teams = viewModel.teams(), team1 = teams[index], team2 = teams[(index + 1) % 2], wicketFalled = getRandomInt(0, 5) == 3 ? true : false; // Assuming that the wicket will only fall when a 0-5 random number is 3 team1.runs += getRandomInt(0, 6); // Get a random score between 0 to 6 team1.wickets += wicketFalled ? 1 : 0; team1.balls += 1; team1.oversText = truncate(team1.balls / 6).toString() + '.' + (team1.balls % 6).toString(); chat.server.updateScore(JSON.stringify(teams)); if (team1.balls === 12 && team2.balls === 12) { $('#updateScoreLink').hide(); var message = (team1.runs > team2.runs ? team1.team : team2.team) + ' won'; message = team1.runs === team2.runs ? 'match tied' : message; message += '\n' + team1.team + ': ' + team1.runs + '/' + team1.wickets + ' overs: ' + team1.oversText; message += '\n' + team2.team + ': ' + team2.runs + '/' + team2.wickets + ' overs: ' + team2.oversText; chat.server.matchFinished(message); } else if (team1.balls === 12) { index = 1;// second team batting } viewModel.teams([team1,team2]); }); }); ko.applyBindings(viewModel); if (isAdmin()) { $('#updateScore').show(); } function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function truncate(n) { return Math[n > 0 ? "floor" : "ceil"](n); } function isAdmin(){ // For demo, assuming that only admin can update the score // and the admin will be user which have admin querystring. return location.href.indexOf('admin=') > -1 } });
In the above scripts, we are initializing SignalR hub cricketHub object(we will see this hub class shortly), viewModel object which include team information(runs, wickets, etc) and index which represent the current batting team. Next, we have two client functions(updateScore and matchFinished) which will be invoked when the server broadcast a message to all clients.
When the hub start, we are registering event handler Update Score click event where we are getting a random run between 0-6, a wicket or not depending upon a random number, updating our view-model and then telling SignalR to broadcast the view-model across all the connected clients so that all clients automatically update their scorecard. Finally, when both teams completed their 12 balls, we will send the results to all the connected clients using SignalR. Note that for demo purpose we are only showing the Update Score button to the user which have admin= query-string.
Finally, here is our CricketHub class,
public class CricketHub : Hub { public void UpdateScore(string teams) { Clients.All.UpdateScore(teams); } public void MatchFinished(string result) { Clients.All.MatchFinished(result); } }
Summary:
In this article, I showed you one of the usage of ASP.NET SignalR. You have seen that how easily we can create a real-time Live Cricket Score using the power of ASP.NET SignalR which works in every browser . Hopefully you will enjoy my this article too.
Published at DZone with permission of Imran Baloch, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments