[SignalR Learning Series] 3. SignalR real-time high refresh rate program, signalr refresh rate

Source: Internet
Author: User

[SignalR Learning Series] 3. SignalR real-time high refresh rate program, signalr refresh rate
Create a project

Create an empty Web project and add the SignalR and jQuery UI packages in Nuget. After adding the packages, the project contains the jQuery, jQuery. UI, and SignalR scripts.

 

Create basic application

Add a SignalR Hub class, name it MoveShapeHub, and update the code.

using Microsoft.AspNet.SignalR;using Newtonsoft.Json;namespace SignalRDemo3{    public class MoveShapeHub : Hub    {        public void UpdateModel(ShapeModel clientModel)        {            clientModel.LastUpdatedBy = Context.ConnectionId;            // Update the shape model within our broadcaster            Clients.AllExcept(clientModel.LastUpdatedBy).updateShape(clientModel);        }    }    public class ShapeModel    {        // We declare Left and Top as lowercase with         // JsonProperty to sync the client and server models        [JsonProperty("left")]        public double Left { get; set; }        [JsonProperty("top")]        public double Top { get; set; }        // We don't want the client to get the "LastUpdatedBy" property        [JsonIgnore]        public string LastUpdatedBy { get; set; }    }}

Start the Hub when the program starts.

Add the Owin class and configure SignalR

using Microsoft.Owin;using Owin;[assembly: OwinStartup(typeof(SignalRDemo3.Startup))]namespace SignalRDemo3{    public class Startup    {        public void Configuration(IAppBuilder app)        {            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888            app.MapSignalR();        }    }}

 

Add Client

Add an html page named Index and set it to the startup page.

<!DOCTYPE html>

The preceding Html and JavaScript code creates a Div named Shape, provides the drag and drop function for Shape through the jQuery library, and sends the current position of Shape to the server through the drag event.

Now you can start F5 debugging to see the effect. After the program is started, open another browser window and enter the address. You can drag and drop the red Shape in one window, and the Shape of the other window will also change.

 

 

Add client Loop

If data is sent to the server every time you move the mouse, a lot of network traffic is required. We must reduce the frequency of data transmission. We can use the setInterval function to set a fixed time to send data to the server.

<!DOCTYPE html>

You can use the above Code to update the Index.html page, and then debug it with F5. You can find that the Shape in another browser will be updated in half a second after dragging a Shape.

 

Add Server cycle

Update MoveShapeHub. cs

using Microsoft.AspNet.SignalR;using Newtonsoft.Json;using System;using System.Threading;namespace SignalRDemo3{    public class Broadcaster    {        private readonly static Lazy<Broadcaster> _instance =            new Lazy<Broadcaster>(() => new Broadcaster());        // We're going to broadcast to all clients once 2 second        private readonly TimeSpan BroadcastInterval =            TimeSpan.FromMilliseconds(2000);        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;            }        }    }    public class MoveShapeHub : Hub    {        // Is set via the constructor on each creation        private Broadcaster _broadcaster;        public MoveShapeHub()            : this(Broadcaster.Instance)        {        }        public MoveShapeHub(Broadcaster broadcaster)        {            _broadcaster = broadcaster;        }        public void UpdateModel(ShapeModel clientModel)        {            clientModel.LastUpdatedBy = Context.ConnectionId;            // Update the shape model within our broadcaster            _broadcaster.UpdateShape(clientModel);        }    }    public class ShapeModel    {        // We declare Left and Top as lowercase with         // JsonProperty to sync the client and server models        [JsonProperty("left")]        public double Left { get; set; }        [JsonProperty("top")]        public double Top { get; set; }        // We don't want the client to get the "LastUpdatedBy" property        [JsonIgnore]        public string LastUpdatedBy { get; set; }    }}

The code above creates a new Broadcaster class, which uses the Timer class for throttling.

Because the Hub instance is re-created each time, only one Broadcaster Singleton model can be created. The method that calls the client UpdateShape is removed from the hub. Now it is managed through the Broadcaster class and updated every two seconds through the timer named _ broadcastLoop.

Finally, because the client method cannot be called directly in the hub, the Broadcaster class needs to use GlobalHost to obtain the hub for the current operation.

In the end, F5 is used for debugging. Although the client is set to refresh once every half a second, because the server is set to refresh once every two seconds, you can move the Shape in the current browser, after two seconds, the Shape in another browser will be moved to the current position.

 

Source code link:

Link: https://pan.baidu.com/s/1o8NXwTW password: 5r5i

 

Reference link:

Https://docs.microsoft.com/zh-cn/aspnet/signalr/overview/getting-started/tutorial-high-frequency-realtime-with-signalr

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.