Tutorial: Server Broadcast with ASP.NET SignalR 1.x
by Patrick Fletcher, Tom Dykstra
This tutorial shows how to create a web application that uses ASP.NET SignalR to provide server broadcast functionality. Server broadcast means that communications sent to clients are initiated by the server. This scenario requires a different programming approach than peer-to-peer scenarios such as chat applications, in which communications sent to clients are initiated by one or more of the clients.
The application that you’ll create in this tutorial simulates a stock ticker, a typical scenario for server broadcast functionality.
Comments on the tutorial are welcome. If you have questions that are not directly related to the tutorial, you can post them to the ASP.NET SignalR forum or StackOverflow.com.
Overview
The Microsoft.AspNet.SignalR.Sample NuGet package installs a sample simulated stock ticker application in a Visual Studio project. In the first part of this tutorial, you’ll create a simplified version of that application from scratch. In the remainder of the tutorial, you’ll install the NuGet package and review the additional features and code that it creates.
The stock ticker application is a representative of a kind of real-time application in which you want to periodically “push,” or broadcast, notifications from the server to all connected clients.
The application that you’ll build in the first part of this tutorial displays a grid with stock data.
Periodically the server randomly updates stock prices and pushes the updates to all connected clients. In the browser the numbers and symbols in the Change and % columns dynamically change in response to notifications from the server. If you open additional browsers to the same URL, they all show the same data and the same changes to the data simultaneously.
This tutorial contains the following sections:
- Prerequisites
- Create the project
- Add the SignalR NuGet packages
- Set up the server code
- Set up the client code
- Test the application
- Enable logging
- Install and review the full StockTicker sample
- Next steps
[!NOTE] If you don’t want to work through the steps of building the application, you can install the SignalR.Sample package in a new Empty ASP.NET Web Application project, and read through these steps to get explanations of the code. The first part of the tutorial covers a subset of the SignalR.Sample code, and the second part explains key features of the additional functionality in the SignalR.Sample package.
Prerequisites
Before you start, make sure that you have Visual Studio 2012 or 2010 SP1 installed on your computer. If you don’t have Visual Studio, see ASP.NET Downloads to get the free Visual Studio 2012 Express for Web.
If you have Visual Studio 2010, make sure that NuGet is installed.
Create the project
- From the File menu click New Project.
- In the New Project dialog box, expand C# under Templates and select Web.
Select the ASP.NET Empty Web Application template, name the project SignalR.StockTicker, and click OK.
Add the SignalR NuGet Packages
Add the SignalR and JQuery NuGet Packages
You can add SignalR functionality to a project by installing a NuGet package.
- Click Tools | Library Package Manager | Package Manager Console.
Enter the following command in the package manager.
[!code-powershellMain]
1: Install-Package Microsoft.AspNet.SignalR -Version 1.1.3
The SignalR package installs a number of other NuGet packages as dependencies. When the installation is finished you have all of the server and client components required to use SignalR in an ASP.NET application.
Set up the server code
In this section you set up the code that runs on the server.
Create the Stock class
You begin by creating the Stock model class that you’ll use to store and transmit information about a stock.
Create a new class file in the project folder, name it Stock.cs, and then replace the template code with the following code:
[!code-csharpMain]
1: using System;
2:
3: namespace SignalR.StockTicker
4: {
5: public class Stock
6: {
7: private decimal _price;
8:
9: public string Symbol { get; set; }
10:
11: public decimal Price
12: {
13: get
14: {
15: return _price;
16: }
17: set
18: {
19: if (_price == value)
20: {
21: return;
22: }
23:
24: _price = value;
25:
26: if (DayOpen == 0)
27: {
28: DayOpen = _price;
29: }
30: }
31: }
32:
33: public decimal DayOpen { get; private set; }
34:
35: public decimal Change
36: {
37: get
38: {
39: return Price - DayOpen;
40: }
41: }
42:
43: public double PercentChange
44: {
45: get
46: {
47: return (double)Math.Round(Change / Price, 4);
48: }
49: }
50: }
51: }
The two properties that you’ll set when you create stocks are the Symbol (for example, MSFT for Microsoft) and the Price. The other properties depend on how and when you set Price. The first time you set Price, the value gets propagated to DayOpen. Subsequent times when you set Price, the Change and PercentChange property values are calculated based on the difference between Price and DayOpen.
Create the StockTicker and StockTickerHub classes
You’ll use the SignalR Hub API to handle server-to-client interaction. A StockTickerHub class that derives from the SignalR Hub class will handle receiving connections and method calls from clients. You also need to maintain stock data and run a Timer object to periodically trigger price updates, independently of client connections. You can’t put these functions in a Hub class, because Hub instances are transient. A Hub class instance is created for each operation on the hub, such as connections and calls from the client to the server. So the mechanism that keeps stock data, updates prices, and broadcasts the price updates has to run in a separate class, which you’ll name StockTicker.
You only want one instance of the StockTicker class to run on the server, so you’ll need to set up a reference from each StockTickerHub instance to the singleton StockTicker instance. The StockTicker class has to be able to broadcast to clients because it has the stock data and triggers updates, but StockTicker is not a Hub class. Therefore, the StockTicker class has to get a reference to the SignalR Hub connection context object. It can then use the SignalR connection context object to broadcast to clients.
- In Solution Explorer, right-click the project and click Add New Item.
- If you have Visual Studio 2012 with the ASP.NET and Web Tools 2012.2 Update, click Web under Visual C# and select the SignalR Hub Class item template. Otherwise, select the Class template.
Name the new class StockTickerHub.cs, and then click Add.
Replace the template code with the following code:
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using Microsoft.AspNet.SignalR;
6: using Microsoft.AspNet.SignalR.Hubs;
7:
8: namespace SignalR.StockTicker
9: {
10: [HubName("stockTickerMini")]
11: public class StockTickerHub : Hub
12: {
13: private readonly StockTicker _stockTicker;
14:
15: public StockTickerHub() : this(StockTicker.Instance) { }
16:
17: public StockTickerHub(StockTicker stockTicker)
18: {
19: _stockTicker = stockTicker;
20: }
21:
22: public IEnumerable<Stock> GetAllStocks()
23: {
24: return _stockTicker.GetAllStocks();
25: }
26: }
27: }
The Hub class is used to define methods the clients can call on the server. You are defining one method:
GetAllStocks()
. When a client initially connects to the server, it will call this method to get a list of all of the stocks with their current prices. The method can execute synchronously and returnIEnumerable<Stock>
because it is returning data from memory. If the method had to get the data by doing something that would involve waiting, such as a database lookup or a web service call, you would specifyTask<IEnumerable<Stock>>
as the return value to enable asynchronous processing. For more information, see ASP.NET SignalR Hubs API Guide - Server - When to execute asynchronously.The HubName attribute specifies how the Hub will be referenced in JavaScript code on the client. The default name on the client if you don’t use this attribute is a camel-cased version of the class name, which in this case would be stockTickerHub.
As you’ll see later when you create the StockTicker class, a singleton instance of that class is created in its static Instance property. That singleton instance of StockTicker remains in memory no matter how many clients connect or disconnect, and that instance is what the GetAllStocks method uses to return current stock information.Create a new class file in the project folder, name it StockTicker.cs, and then replace the template code with the following code:
[!code-csharpMain]
1: using System;
2: using System.Collections.Concurrent;
3: using System.Collections.Generic;
4: using System.Threading;
5: using Microsoft.AspNet.SignalR;
6: using Microsoft.AspNet.SignalR.Hubs;
7:
8: namespace SignalR.StockTicker
9: {
10: public class StockTicker
11: {
12: // Singleton instance
13: private readonly static Lazy<StockTicker> _instance = new Lazy<StockTicker>(() => new StockTicker(GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>().Clients));
14:
15: private readonly ConcurrentDictionary<string, Stock> _stocks = new ConcurrentDictionary<string, Stock>();
16:
17: private readonly object _updateStockPricesLock = new object();
18:
19: //stock can go up or down by a percentage of this factor on each change
20: private readonly double _rangePercent = .002;
21:
22: private readonly TimeSpan _updateInterval = TimeSpan.FromMilliseconds(250);
23: private readonly Random _updateOrNotRandom = new Random();
24:
25: private readonly Timer _timer;
26: private volatile bool _updatingStockPrices = false;
27:
28: private StockTicker(IHubConnectionContext clients)
29: {
30: Clients = clients;
31:
32: _stocks.Clear();
33: var stocks = new List<Stock>
34: {
35: new Stock { Symbol = "MSFT", Price = 30.31m },
36: new Stock { Symbol = "APPL", Price = 578.18m },
37: new Stock { Symbol = "GOOG", Price = 570.30m }
38: };
39: stocks.ForEach(stock => _stocks.TryAdd(stock.Symbol, stock));
40:
41: _timer = new Timer(UpdateStockPrices, null, _updateInterval, _updateInterval);
42:
43: }
44:
45: public static StockTicker Instance
46: {
47: get
48: {
49: return _instance.Value;
50: }
51: }
52:
53: private IHubConnectionContext Clients
54: {
55: get;
56: set;
57: }
58:
59: public IEnumerable<Stock> GetAllStocks()
60: {
61: return _stocks.Values;
62: }
63:
64: private void UpdateStockPrices(object state)
65: {
66: lock (_updateStockPricesLock)
67: {
68: if (!_updatingStockPrices)
69: {
70: _updatingStockPrices = true;
71:
72: foreach (var stock in _stocks.Values)
73: {
74: if (TryUpdateStockPrice(stock))
75: {
76: BroadcastStockPrice(stock);
77: }
78: }
79:
80: _updatingStockPrices = false;
81: }
82: }
83: }
84:
85: private bool TryUpdateStockPrice(Stock stock)
86: {
87: // Randomly choose whether to udpate this stock or not
88: var r = _updateOrNotRandom.NextDouble();
89: if (r > .1)
90: {
91: return false;
92: }
93:
94: // Update the stock price by a random factor of the range percent
95: var random = new Random((int)Math.Floor(stock.Price));
96: var percentChange = random.NextDouble() * _rangePercent;
97: var pos = random.NextDouble() > .51;
98: var change = Math.Round(stock.Price * (decimal)percentChange, 2);
99: change = pos ? change : -change;
100:
101: stock.Price += change;
102: return true;
103: }
104:
105: private void BroadcastStockPrice(Stock stock)
106: {
107: Clients.All.updateStockPrice(stock);
108: }
109:
110: }
111: }
Since multiple threads will be running the same instance of StockTicker code, the StockTicker class has to be threadsafe.
### Storing the singleton instance in a static field
The code initializes the static _instance field that backs the Instance property with an instance of the class, and this is the only instance of the class that can be created, because the constructor is marked as private. Lazy initialization is used for the _instance field, not for performance reasons but to ensure that the instance creation is threadsafe.
[!code-csharpMain]
1: private readonly static Lazy<StockTicker> _instance = new Lazy<StockTicker>(() => new StockTicker(GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>().Clients));
2:
3: public static StockTicker Instance
4: {
5: get
6: {
7: return _instance.Value;
8: }
9: }
Each time a client connects to the server, a new instance of the StockTickerHub class running in a separate thread gets the StockTicker singleton instance from the StockTicker.Instance static property, as you saw earlier in the StockTickerHub class.
### Storing stock data in a ConcurrentDictionary
The constructor initializes the _stocks collection with some sample stock data, and GetAllStocks returns the stocks. As you saw earlier, this collection of stocks is in turn returned by StockTickerHub.GetAllStocks which is a server method in the Hub class that clients can call.
[!code-csharpMain]
1: private readonly ConcurrentDictionary<string, Stock> _stocks = new ConcurrentDictionary<string, Stock>();
[!code-csharpMain]
1: private StockTicker(IHubConnectionContext clients)
2: {
3: Clients = clients;
4:
5: _stocks.Clear();
6: var stocks = new List<Stock>
7: {
8: new Stock { Symbol = "MSFT", Price = 30.31m },
9: new Stock { Symbol = "APPL", Price = 578.18m },
10: new Stock { Symbol = "GOOG", Price = 570.30m }
11: };
12: stocks.ForEach(stock => _stocks.TryAdd(stock.Symbol, stock));
13:
14: _timer = new Timer(UpdateStockPrices, null, _updateInterval, _updateInterval);
15: }
16:
17: public IEnumerable<Stock> GetAllStocks()
18: {
19: return _stocks.Values;
20: }
The stocks collection is defined as a ConcurrentDictionary type for thread safety. As an alternative, you could use a Dictionary object and explicitly lock the dictionary when you make changes to it.
For this sample application, it’s OK to store application data in memory and to lose the data when the StockTicker instance is disposed. In a real application you would work with a back-end data store such as a database.
### Periodically updating stock prices
The constructor starts up a Timer object that periodically calls methods that update stock prices on a random basis.
[!code-csharpMain]
1: _timer = new Timer(UpdateStockPrices, null, _updateInterval, _updateInterval);
2:
3: private void UpdateStockPrices(object state)
4: {
5: lock (_updateStockPricesLock)
6: {
7: if (!_updatingStockPrices)
8: {
9: _updatingStockPrices = true;
10:
11: foreach (var stock in _stocks.Values)
12: {
13: if (TryUpdateStockPrice(stock))
14: {
15: BroadcastStockPrice(stock);
16: }
17: }
18:
19: _updatingStockPrices = false;
20: }
21: }
22: }
23:
24: private bool TryUpdateStockPrice(Stock stock)
25: {
26: // Randomly choose whether to update this stock or not
27: var r = _updateOrNotRandom.NextDouble();
28: if (r > .1)
29: {
30: return false;
31: }
32:
33: // Update the stock price by a random factor of the range percent
34: var random = new Random((int)Math.Floor(stock.Price));
35: var percentChange = random.NextDouble() * _rangePercent;
36: var pos = random.NextDouble() > .51;
37: var change = Math.Round(stock.Price * (decimal)percentChange, 2);
38: change = pos ? change : -change;
39:
40: stock.Price += change;
41: return true;
42: }
UpdateStockPrices is called by the Timer, which passes in null in the state parameter. Before updating prices, a lock is taken on the _updateStockPricesLock object. The code checks if another thread is already updating prices, and then it calls TryUpdateStockPrice on each stock in the list. The TryUpdateStockPrice method decides whether to change the stock price, and how much to change it. If the stock price is changed, BroadcastStockPrice is called to broadcast the stock price change to all connected clients.
The _updatingStockPrices flag is marked as volatile to ensure that access to it is threadsafe.
[!code-csharpMain]
1: private volatile bool _updatingStockPrices = false;
In a real application, the TryUpdateStockPrice method would call a web service to look up the price; in this code it uses a random number generator to make changes randomly.
### Getting the SignalR context so that the StockTicker class can broadcast to clients
Because the price changes originate here in the StockTicker object, this is the object that needs to call an updateStockPrice method on all connected clients. In a Hub class you have an API for calling client methods, but StockTicker does not derive from the Hub class and does not have a reference to any Hub object. Therefore, in order to broadcast to connected clients, the StockTicker class has to get the SignalR context instance for the StockTickerHub class and use that to call methods on clients.
The code gets a reference to the SignalR context when it creates the singleton class instance, passes that reference to the constructor, and the constructor puts it in the Clients property.
There are two reasons why you want to get the context just once: getting the context is an expensive operation, and getting it once ensures that the intended order of messages sent to clients is preserved.
[!code-csharpMain]
1: private readonly static Lazy<StockTicker> _instance =
2: new Lazy<StockTicker>(() => new StockTicker(GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>().Clients));
3:
4: private StockTicker(IHubConnectionContext clients)
5: {
6: Clients = clients;
7:
8: // Remainder of constructor ...
9: }
10:
11: private IHubConnectionContext Clients
12: {
13: get;
14: set;
15: }
16:
17: private void BroadcastStockPrice(Stock stock)
18: {
19: Clients.All.updateStockPrice(stock);
20: }
Getting the Clients property of the context and putting it in the StockTickerClient property lets you write code to call client methods that looks the same as it would in a Hub class. For instance, to broadcast to all clients you can write Clients.All.updateStockPrice(stock).
The updateStockPrice method that you are calling in BroadcastStockPrice doesn’t exist yet; you’ll add it later when you write code that runs on the client. You can refer to updateStockPrice here because Clients.All is dynamic, which means the expression will be evaluated at runtime. When this method call executes, SignalR will send the method name and the parameter value to the client, and if the client has a method named updateStockPrice, that method will be called and the parameter value will be passed to it.
Clients.All means send to all clients. SignalR gives you other options to specify which clients or groups of clients to send to. For more information, see HubConnectionContext.
Register the SignalR route
The server needs to know which URL to intercept and direct to SignalR. To do that you’ll add some code to the Global.asax file.
- In Solution Explorer, right-click the project, and then click Add New Item.
Select the Global Application Class item template, and then click Add.
Add the SignalR route registration code to the Application_Start method:
[!code-csharpMain]
1: protected void Application_Start(object sender, EventArgs e)
2: {
3: RouteTable.Routes.MapHubs();
4: }
Add a using statement at the top of the file:
[!code-csharpMain]1: using System.Web.Routing;
Save and close the Global.asax file, and build the project.
You have now completed setting up the server code. In the next section you’ll set up the client.
Set up the client code
- Create a new HTML file in the project folder, and name it StockTicker.html.
Replace the template code with the following code:
[!code-htmlMain]
1: <!DOCTYPE html>
2: <html xmlns="http://www.w3.org/1999/xhtml">
3: <head>
4: <title>ASP.NET SignalR Stock Ticker</title>
5: <style>
6: body {
7: font-family: 'Segoe UI', Arial, Helvetica, sans-serif;
8: font-size: 16px;
9: }
10: #stockTable table {
11: border-collapse: collapse;
12: }
13: #stockTable table th, #stockTable table td {
14: padding: 2px 6px;
15: }
16: #stockTable table td {
17: text-align: right;
18: }
19: #stockTable .loading td {
20: text-align: left;
21: }
22: </style>
23: </head>
24: <body>
25: <h1>ASP.NET SignalR Stock Ticker Sample</h1>
26:
27: <h2>Live Stock Table</h2>
28: <div id="stockTable">
29: <table border="1">
30: <thead>
31: <tr><th>Symbol</th><th>Price</th><th>Open</th><th>Change</th><th>%</th></tr>
32: </thead>
33: <tbody>
34: <tr class="loading"><td colspan="5">loading...</td></tr>
35: </tbody>
36: </table>
37: </div>
38:
39: <!--Script references. -->
40: <!--Reference the jQuery library. -->
41: <script src="/Scripts/jquery-1.8.2.min.js" ></script>
42: <!--Reference the SignalR library. -->
43: <script src="/Scripts/jquery.signalR-1.0.1.js"></script>
44: <!--Reference the autogenerated SignalR hub script. -->
45: <script src="/signalr/hubs"></script>
46: <!--Reference the StockTicker script. -->
47: <script src="StockTicker.js"></script>
48: </body>
49: </html>
The HTML creates a table with 5 columns, a header row, and a data row with a single cell that spans all 5 columns. The data row displays “loading…” and will only be shown momentarily when the application starts. JavaScript code will remove that row and add in its place rows with stock data retrieved from the server.
The script tags specify the jQuery script file, the SignalR core script file, the SignalR proxies script file, and a StockTicker script file that you’ll create later. The SignalR proxies script file, which specifies the “/signalr/hubs” URL, is dynamically generated and defines proxy methods for the methods on the Hub class, in this case for StockTickerHub.GetAllStocks. If you prefer, you can generate this JavaScript file manually by using SignalR Utilities and disable dynamic file creation in the MapHubs method call.[!IMPORTANT] Make sure that the JavaScript file references in StockTicker.html are correct. That is, make sure that the jQuery version in your script tag (1.8.2 in the example) is the same as the jQuery version in your project’s Scripts folder, and make sure that the SignalR version in your script tag is the same as the SignalR version in your project’s Scripts folder. Change the file names in the script tags if necessary.
- In Solution Explorer, right-click StockTicker.html, and then click Set as Start Page.
- Create a new JavaScript file in the project folder and name it StockTicker.js..
Replace the template code with the following code:
[!code-javascriptMain]
1: // A simple templating method for replacing placeholders enclosed in curly braces.
2: if (!String.prototype.supplant) {
3: String.prototype.supplant = function (o) {
4: return this.replace(/{([^{}]*)}/g,
5: function (a, b) {
6: var r = o[b];
7: return typeof r === 'string' || typeof r === 'number' ? r : a;
8: }
9: );
10: };
11: }
12:
13: $(function () {
14:
15: var ticker = $.connection.stockTickerMini, // the generated client-side hub proxy
16: up = '▲',
17: down = '▼',
18: $stockTable = $('#stockTable'),
19: $stockTableBody = $stockTable.find('tbody'),
20: rowTemplate = '<tr data-symbol="{Symbol}"><td>{Symbol}</td><td>{Price}</td><td>{DayOpen}</td><td>{Direction} {Change}</td><td>{PercentChange}</td></tr>';
21:
22: function formatStock(stock) {
23: return $.extend(stock, {
24: Price: stock.Price.toFixed(2),
25: PercentChange: (stock.PercentChange * 100).toFixed(2) + '%',
26: Direction: stock.Change === 0 ? '' : stock.Change >= 0 ? up : down
27: });
28: }
29:
30: function init() {
31: ticker.server.getAllStocks().done(function (stocks) {
32: $stockTableBody.empty();
33: $.each(stocks, function () {
34: var stock = formatStock(this);
35: $stockTableBody.append(rowTemplate.supplant(stock));
36: });
37: });
38: }
39:
40: // Add a client-side hub method that the server will call
41: ticker.client.updateStockPrice = function (stock) {
42: var displayStock = formatStock(stock),
43: $row = $(rowTemplate.supplant(displayStock));
44:
45: $stockTableBody.find('tr[data-symbol=' + stock.Symbol + ']')
46: .replaceWith($row);
47: }
48:
49: // Start the connection
50: $.connection.hub.start().done(init);
51:
52: });
$.connection refers to the SignalR proxies. The code gets a reference to the proxy for the StockTickerHub class and puts it in the ticker variable. The proxy name is the name that was set by the [HubName] attribute:
[!code-javascriptMain]
1: var ticker = $.connection.stockTickerMini
[!code-csharpMain]
1: [HubName("stockTickerMini")]
2: public class StockTickerHub : Hub
After all the variables and functions are defined, the last line of code in the file initializes the SignalR connection by calling the SignalR start function. The start function executes asynchronously and returns a jQuery Deferred object, which means you can call the done function to specify the function to call when the asynchronous operation is completed..
[!code-javascriptMain]
1: $.connection.hub.start().done(init);
The init function calls the getAllStocks function on the server and uses the information that the server returns to update the stock table. Notice that by default, you have to use camel casing on the client although the method name is pascal-cased on the server. The camel-casing rule only applies to methods, not objects. For example, you refer to stock.Symbol and stock.Price, not stock.symbol or stock.price.
[!code-javascriptMain]
1: function init() {
2: ticker.server.getAllStocks().done(function (stocks) {
3: $stockTableBody.empty();
4: $.each(stocks, function () {
5: var stock = formatStock(this);
6: $stockTableBody.append(rowTemplate.supplant(stock));
7: });
8: });
9: }
[!code-csharpMain]
1: public IEnumerable<Stock> GetAllStocks()
2: {
3: return _stockTicker.GetAllStocks();
4: }
If you wanted to use pascal casing on the client, or if you wanted to use a completely different method name, you could decorate the Hub method with the HubMethodName attribute the same way you decorated the Hub class itself with the HubName attribute.
In the init method, HTML for a table row is created for each stock object received from the server by calling formatStock to format properties of the stock object, and then by calling supplant (which is defined at the top of StockTicker.js) to replace placeholders in the rowTemplate variable with the stock object property values. The resulting HTML is then appended to the stock table.
You call init by passing it in as a callback function that executes after the asynchronous start function completes. If you called init as a separate JavaScript statement after calling start, the function would fail because it would execute immediately without waiting for the start function to finish establishing the connection. In that case, the init function would try to call the getAllStocks function before the server connection is established.
When the server changes a stock’s price, it calls the updateStockPrice on connected clients. The function is added to the client property of the stockTicker proxy in order to make it available to calls from the server.
[!code-javascriptMain]
1: ticker.client.updateStockPrice = function (stock) {
2: var displayStock = formatStock(stock),
3: $row = $(rowTemplate.supplant(displayStock));
4:
5: $stockTableBody.find('tr[data-symbol=' + stock.Symbol + ']')
6: .replaceWith($row);
7: }
The updateStockPrice function formats a stock object received from the server into a table row the same way as in the init function. However, instead of appending the row to the table, it finds the stock’s current row in the table and replaces that row with the new one.
Test the application
Press F5 to run the application in debug mode.
The stock table initially displays the “loading…” line, then after a short delay the initial stock data is displayed, and then the stock prices start to change.
Copy the URL from the browser address bar and paste it into one or more new browser window(s).
The initial stock display is the same as the first browser and changes happen simultaneously.Close all browsers and open a new browser, then go to the same URL.
The StockTicker singleton object has continued to run in the server, so the stock table display shows that the stocks have continued to change. (You don’t see the initial table with zero change figures.)Close the browser.
Enable logging
SignalR has a built-in logging function that you can enable on the client to aid in troubleshooting. In this section you enable logging and see examples that show how logs tell you which of the following transport methods SignalR is using:
- WebSockets, supported by IIS 8 and current browsers.
- Server-sent events, supported by browsers other than Internet Explorer.
- Forever frame, supported by Internet Explorer.
- Ajax long polling, supported by all browsers.
For any given connection, SignalR chooses the best transport method that both the server and the client support.
Open StockTicker.js and add a line of code to enable logging immediately before the code that initializes the connection at the end of the file:
[!code-javascriptMain]1: // Start the connection
2: $.connection.hub.logging = true;
3: $.connection.hub.start().done(init);
- Press F5 to run the project.
Open your browser’s developer tools window, and select the Console to see the logs. You might have to refresh the page to see the logs of Signalr negotiating the transport method for a new connection.
If you are running Internet Explorer 10 on Windows 8 (IIS 8), the transport method is WebSockets.
If you are running Internet Explorer 10 on Windows 7 (IIS 7.5), the transport method is iframe.
In Firefox, install the Firebug add-in to get a Console window. If you are running Firefox 19 on Windows 8 (IIS 8), the transport method is WebSockets.
If you are running Firefox 19 on Windows 7 (IIS 7.5), the transport method is server-sent events.
Install and review the full StockTicker sample
The StockTicker application that is installed by the Microsoft.AspNet.SignalR.Sample NuGet package includes more features than the simplified version that you just created from scratch. In this section of the tutorial, you install the NuGet package and review the new features and the code that implements them.
Install the SignalR.Sample NuGet package
- In Solution Explorer, right-click the project and click Manage NuGet Packages.
In the Manage NuGet Packages dialog box, click Online, enter SignalR.Sample in the Search Online box, and then click Install in the SignalR.Sample package.
In the Global.asax file, comment out the RouteTable.Routes.MapHubs(); line that you added earlier in the Application_Start method.
The code in Global.asax is no longer needed because the SignalR.Sample package registers the SignalR route in the App_Start/RegisterHubs.cs file:
[!code-csharpMain]
1: [assembly: WebActivator.PreApplicationStartMethod(typeof(SignalR.StockTicker.RegisterHubs), "Start")]
2:
3: namespace SignalR.StockTicker
4: {
5: public static class RegisterHubs
6: {
7: public static void Start()
8: {
9: // Register the default hubs route: ~/signalr/hubs
10: RouteTable.Routes.MapHubs();
11: }
12: }
13: }
- In Solution Explorer, expand the SignalR.Sample folder which was created by installing the SignalR.Sample package.
In the SignalR.Sample folder, right-click StockTicker.html, and then click Set As Start Page.
[!NOTE] Installing The SignalR.Sample NuGet package might change the version of jQuery that you have in your Scripts folder. The new StockTicker.html file that the package installs in the SignalR.Sample folder will be in sync with the jQuery version that the package installs, but if you want to run your original StockTicker.html file again, you might have to update the jQuery reference in the script tag first.
Run the application
Press F5 to run the application.
In addition to the grid that you saw earlier, the full stock ticker application shows a horizontally scrolling window that displays the same stock data. When you run the application for the first time, the “market” is “closed” and you see a static grid and a ticker window that isn’t scrolling.
When you click Open Market, the Live Stock Ticker box starts to scroll horizontally, and the server starts to periodically broadcast stock price changes on a random basis. Each time a stock price changes, both the Live Stock Table grid and the Live Stock Ticker box are updated. When a stock’s price change is positive, the stock is shown with a green background, and when the change is negative, the stock is shown with a red background.
The Close Market button stops the changes and stops the ticker scrolling, and the Reset button resets all stock data to the initial state before price changes started. If you open more browser windows and go to the same URL, you see the same data dynamically updated at the same time in each browser. When you click one of the buttons, all browsers respond the same way at the same time.
Live Stock Ticker display
The Live Stock Ticker display is an unordered list in a div element that is formatted into a single line by CSS styles. The ticker is initialized and updated the same way as the table: by replacing placeholders in a <li> template string and dynamically adding the <li> elements to the <ul> element. The scrolling is performed by using the jQuery animate function to vary the margin-left of the unordered list within the div.
The stock ticker HTML:
[!code-htmlMain]
1: <h2>Live Stock Ticker</h2>
2: <div id="stockTicker">
3: <div class="inner">
4: <ul>
5: <li class="loading">loading...</li>
6: </ul>
7: </div>
8: </div>
The stock ticker CSS:
[!code-htmlMain]
1: #stockTicker {
2: overflow: hidden;
3: width: 450px;
4: height: 24px;
5: border: 1px solid #999;
6: }
7:
8: #stockTicker .inner {
9: width: 9999px;
10: }
11:
12: #stockTicker ul {
13: display: inline-block;
14: list-style-type: none;
15: margin: 0;
16: padding: 0;
17: }
18:
19: #stockTicker li {
20: display: inline-block;
21: margin-right: 8px;
22: }
23:
24: /*<li data-symbol="{Symbol}"><span class="symbol">{Symbol}</span><span class="price">{Price}</span><span class="change">{PercentChange}</span></li>*/
25: #stockTicker .symbol {
26: font-weight: bold;
27: }
28:
29: #stockTicker .change {
30: font-style: italic;
31: }
The jQuery code that makes it scroll:
[!code-javascriptMain]
1: function scrollTicker() {
2: var w = $stockTickerUl.width();
3: $stockTickerUl.css({ marginLeft: w });
4: $stockTickerUl.animate({ marginLeft: -w }, 15000, 'linear', scrollTicker);
5: }
Additional methods on the server that the client can call
The StockTickerHub class defines four additional methods that the client can call:
[!code-csharpMain]
1: public string GetMarketState()
2: {
3: return _stockTicker.MarketState.ToString();
4: }
5:
6: public void OpenMarket()
7: {
8: _stockTicker.OpenMarket();
9: }
10:
11: public void CloseMarket()
12: {
13: _stockTicker.CloseMarket();
14: }
15:
16: public void Reset()
17: {
18: _stockTicker.Reset();
19: }
OpenMarket, CloseMarket, and Reset are called in response to the buttons at the top of the page. They demonstrate the pattern of one client triggering a change in state that is immediately propagated to all clients. Each of these methods calls a method in the StockTicker class that effects the market state change and then broadcasts the new state.
In the StockTicker class, the state of the market is maintained by a MarketState property that returns a MarketState enum value:
[!code-csharpMain]
1: public MarketState MarketState
2: {
3: get { return _marketState; }
4: private set { _marketState = value; }
5: }
6:
7: public enum MarketState
8: {
9: Closed,
10: Open
11: }
Each of the methods that change the market state do so inside a lock block because the StockTicker class has to be threadsafe:
[!code-csharpMain]
1: public void OpenMarket()
2: {
3: lock (_marketStateLock)
4: {
5: if (MarketState != MarketState.Open)
6: {
7: _timer = new Timer(UpdateStockPrices, null, _updateInterval, _updateInterval);
8: MarketState = MarketState.Open;
9: BroadcastMarketStateChange(MarketState.Open);
10: }
11: }
12: }
13:
14: public void CloseMarket()
15: {
16: lock (_marketStateLock)
17: {
18: if (MarketState == MarketState.Open)
19: {
20: if (_timer != null)
21: {
22: _timer.Dispose();
23: }
24: MarketState = MarketState.Closed;
25: BroadcastMarketStateChange(MarketState.Closed);
26: }
27: }
28: }
29:
30: public void Reset()
31: {
32: lock (_marketStateLock)
33: {
34: if (MarketState != MarketState.Closed)
35: {
36: throw new InvalidOperationException("Market must be closed before it can be reset.");
37: }
38: LoadDefaultStocks();
39: BroadcastMarketReset();
40: }
41: }
To ensure that this code is threadsafe, the _marketState field that backs the MarketState property is marked as volatile,
[!code-csharpMain]
1: private volatile MarketState _marketState;
The BroadcastMarketStateChange and BroadcastMarketReset methods are similar to the BroadcastStockPrice method that you already saw, except they call different methods defined at the client:
[!code-csharpMain]
1: private void BroadcastMarketStateChange(MarketState marketState)
2: {
3: switch (marketState)
4: {
5: case MarketState.Open:
6: Clients.All.marketOpened();
7: break;
8: case MarketState.Closed:
9: Clients.All.marketClosed();
10: break;
11: default:
12: break;
13: }
14: }
15:
16: private void BroadcastMarketReset()
17: {
18: Clients.All.marketReset();
19: }
Additional functions on the client that the server can call
The updateStockPrice function now handles both the grid and the ticker display, and it uses jQuery.Color to flash red and green colors.
New functions in SignalR.StockTicker.js enable and disable the buttons based on market state, and they stop or start the ticker window horizontal scrolling. Since multiple functions are being added to ticker.client, the jQuery extend function is used to add them.
[!code-javascriptMain]
1: $.extend(ticker.client, {
2: updateStockPrice: function (stock) {
3: var displayStock = formatStock(stock),
4: $row = $(rowTemplate.supplant(displayStock)),
5: $li = $(liTemplate.supplant(displayStock)),
6: bg = stock.LastChange === 0
7: ? '255,216,0' // yellow
8: : stock.LastChange > 0
9: ? '154,240,117' // green
10: : '255,148,148'; // red
11:
12: $stockTableBody.find('tr[data-symbol=' + stock.Symbol + ']')
13: .replaceWith($row);
14: $stockTickerUl.find('li[data-symbol=' + stock.Symbol + ']')
15: .replaceWith($li);
16:
17: $row.flash(bg, 1000);
18: $li.flash(bg, 1000);
19: },
20:
21: marketOpened: function () {
22: $("#open").prop("disabled", true);
23: $("#close").prop("disabled", false);
24: $("#reset").prop("disabled", true);
25: scrollTicker();
26: },
27:
28: marketClosed: function () {
29: $("#open").prop("disabled", false);
30: $("#close").prop("disabled", true);
31: $("#reset").prop("disabled", false);
32: stopTicker();
33: },
34:
35: marketReset: function () {
36: return init();
37: }
38: });
Additional client setup after establishing the connection
After the client establishes the connection, it has some additional work to do: find out if the market is open or closed in order to call the appropriate marketOpened or marketClosed function, and attach the server method calls to the buttons.
[!code-javascriptMain]
1: $.connection.hub.start()
2: .pipe(init)
3: .pipe(function () {
4: return ticker.server.getMarketState();
5: })
6: .done(function (state) {
7: if (state === 'Open') {
8: ticker.client.marketOpened();
9: } else {
10: ticker.client.marketClosed();
11: }
12:
13: // Wire up the buttons
14: $("#open").click(function () {
15: ticker.server.openMarket();
16: });
17:
18: $("#close").click(function () {
19: ticker.server.closeMarket();
20: });
21:
22: $("#reset").click(function () {
23: ticker.server.reset();
24: });
25: });
The server methods are not wired up to the buttons until after the connection is established, so that the code can’t try to call the server methods before they are available.
Next steps
In this tutorial you’ve learned how to program a SignalR application that broadcasts messages from the server to all connected clients, both on a periodic basis and in response to notifications from any client. The pattern of using a multi-threaded singleton instance to maintain server state can also be also used in multi-player online game scenarios. For an example, see the ShootR game that is based on SignalR.
For tutorials that show peer-to-peer communication scenarios, see Getting Started with SignalR and Real-Time Updating with SignalR.
To learn more advanced SignalR development concepts, visit the following sites for SignalR source code and resources:
|