Last active
December 15, 2015 14:28
-
-
Save NTaylorMullen/5274212 to your computer and use it in GitHub Desktop.
Broadcaster for MoveShape REVISION
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using Microsoft.AspNet.SignalR; | |
namespace MoveShape | |
{ | |
public class Broadcaster | |
{ | |
private readonly static Lazy<Broadcaster> _instance = new Lazy<Broadcaster>(() => new Broadcaster()); | |
private readonly TimeSpan BroadcastInterval = TimeSpan.FromMilliseconds(20); // We're going to broadcast to all clients 50 times per second | |
private readonly IHubContext _hubContext; | |
private Timer _broadcastLoop; | |
private ShapeModel _model; | |
private bool _modelUpdated; | |
public Broadcaster() | |
{ | |
// Save our hub context so we can easily use it to send to its connected clients | |
_hubContext = GlobalHost.ConnectionManager.GetHubContext<MoveShapeHub>(); | |
_model = new ShapeModel(); | |
_modelUpdated = false; | |
// Start the broadcast loop | |
_broadcastLoop = new Timer(BroadcastShape, null, BroadcastInterval, BroadcastInterval); | |
} | |
public void BroadcastShape(object state) | |
{ | |
// No need to send anything if our model hasn't changed | |
if (_modelUpdated) | |
{ | |
// This is how we can access the Clients property in a static hub method or outside of the hub entirely | |
_hubContext.Clients.AllExcept(_model.LastUpdatedBy).updateShape(_model); | |
_modelUpdated = false; | |
} | |
} | |
public void UpdateShape(ShapeModel clientModel) | |
{ | |
_model = clientModel; | |
_modelUpdated = true; | |
} | |
public static Broadcaster Instance | |
{ | |
get | |
{ | |
return _instance.Value; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment