About SignalR

table of Contents

Introduction

What is SignalR?

And connecting hub (Hubs)

Creating an application

Adding a client cycle

Add Server circulation

Adding to the client-side smooth animation

reference


Introduction

This tip covers the Web using the application environment SignalR introduced real-time communication of information, which the server can immediately push information to the client when the client is available, rather than waiting for the client to request data from the server.

SignalR for chat applications on the World Wide Web, the dashboard or the game is very useful, but also very important for industrial desktop applications.

If you use AJAX to improve Web application responsive, then SignalR is a useful alternative.

You can be determined by enabling logging SignalR transport type being used:

$.connection.hub.logging = true;

If you followed the Web to open the browser debugging tools, you will see, such as "SignalR : Websocket the Opened" line and the like.

What is SignalR ?

In general, from the server to obtain more data on the client (if changed), you must use HTTP polling GET , which is AJAX doing. If you want any near real thing, then you have to constantly poll. Instead, use SignalR , you have a persistent connection, the client can call the server, the server can call the client.

Therefore, SignalR is a developer library that simplifies real-time communication, which server and client connection is durable, with the traditional HTTP paradigm different.

If your computer is using Windows 8 or Windows Server 2012 or later and the .NET Framework 4.5 , then SignalR will use the WebSocket ; otherwise, it uses HTML 5 transmission or Comet transmission.

And connecting hub (Hubs)

Both models of communication between the client and the server are persistent connections and the hub.

It denotes a transmission connected to a single recipient, a broadcast packet or end of message.

Hub is a persistent connection (Persistent Connections) above a layer that allows your client and the server directly call each other method. Use .NET Remoting in .NET developers will be familiar with this model. This allows you to pass strongly typed parameters.

When the transmission of the complete object via the communication channel, they will use JSON serialized.

You can use Fiddler to call other tools monitoring method.

Creating an application

First, create an empty ASP.NET Web project, right-click to add SignalR , make sure your project for .NET 4.5 or later:

Select SignalR :

Or you can simply enter the Package Manager console:

PM> install-package Microsoft.AspNet.SignalR
PM> install-Package jQuery.UI.Combined
PM> install-Package Microsoft.Web.Infrastructure

Next, called Startup class added to the application, the class mapping application startup SignalR hub:

using Microsoft.AspNet.SignalR;      
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(CodeProjectSignalRSample.Startup))]
namespace CodeProjectSignalRSample
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var hubConfiguration = new HubConfiguration();
            hubConfiguration.EnableDetailedErrors = true;        
        
            app.MapSignalR();
        }
    }
}

If you have not, please add the following SignalR hub categories:

using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;

namespace CodeProjectSignalRSample
{
    public class MyHub : 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; }
    }
}

The client can call UpdateModel method, and then broadcast to all connected clients. It uses JSON automatic serialization.

Now by adding to the solution HTML to add client page:

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Demo</title>
    <style>
        #shape {
            width: 100px;
            height: 100px;
            background-color: #FF0000;
        }
    </style>
</head>
<body>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/jquery-ui-1.10.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.1.0.js"></script>
<script src="/signalr/hubs"></script>
<script>
 $(function () {
            var moveShapeHub = $.connection.myHub,
            $shape = $("#shape"),
            shapeModel = {
                left: 0,
                top: 0
            };
            MyHub.client.updateShape = function (model) {
                shapeModel = model;
                $shape.css({ left: model.left, top: model.top });
            };
            $.connection.hub.start().done(function () {
                $shape.draggable({
                    drag: function () {
                        shapeModel = $shape.offset();
                        MyHub.server.updateModel(shapeModel);
                    }
                });
            });
        });
</script>
    
    <div id="shape" />
</body>
</html>

另外,请确保您的web.config文件包含以下内容:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
</configuration>

启动应用程序,然后将URL复制到浏览器的新实例中。尝试移动形状。

添加客户端循环

在每次鼠标移动时发送位置会产生大量网络流量,因此您可以通过将此代码放入HTML文件来限制它:

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Demo</title>
    <style>
        #shape {
            width: 100px;
            height: 100px;
            background-color: #FF0000;
        }
    </style>
</head>
<body>
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery-ui-1.11.3.min.js"></script>
    <script src="Scripts/jquery.signalR-2.2.0.js"></script>
    <script src="/signalr/hubs"></script>
    <script>
        $(function () {
            var moveShapeHub = $.connection.myHub,
                $shape = $("#shape"),
                // Send a maximum of 10 messages per second
                // (mouse movements trigger a lot of messages)
                messageFrequency = 10,
                // Determine how often to send messages in
                // time to abide by the messageFrequency
                updateRate = 1000 / messageFrequency,
                shapeModel = {
                    left: 0,
                    top: 0
                },
                moved = false;
            moveShapeHub.client.updateShape = function (model) {
                shapeModel = model;
                $shape.css({ left: model.left, top: model.top });
            };
            $.connection.hub.start().done(function () {
                $shape.draggable({
                    drag: function () {
                        shapeModel = $shape.offset();
                        moved = true;
                    }
                });
                // Start the client side server update interval
                setInterval(updateServerModel, updateRate);
            });
            function updateServerModel() {
                // Only update server if we have a new movement
                if (moved) {
                    moveShapeHub.server.updateModel(shapeModel);
                    moved = false;
                }
            }
        });
    </script>

    <div id="shape" />
</body>
</html>

添加服务器循环

将以下代码添加到集线器还可以减少服务器端的流量:

using System;
using System.Threading;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;

namespace CodeProjectSignalRSample
{
    public class Broadcaster
    {
        private readonly static Lazy
 _instance =
            new Lazy
(() => new Broadcaster());
        // We're going to broadcast to all clients a maximum of 25 times per second
        private readonly TimeSpan BroadcastInterval =
            TimeSpan.FromMilliseconds(40);
        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<myhub>();
            _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 MyHub : Hub
    {
        private Broadcaster _broadcaster;
        public MyHub()
            : this(Broadcaster.Instance)
        {
        }

        public MyHub(Broadcaster broadcaster)
        {
            _broadcaster = broadcaster;
        }

        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; }
    }
}

向客户端添加平滑动画

添加以下代码以使形状在1000毫秒的过程中从旧位置移动到新位置:

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Demo</title>
    <style>
        #shape {
            width: 100px;
            height: 100px;
            background-color: #FF0000;
        }
    </style>
</head>
<body>
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery-ui-1.11.3.min.js"></script>
    <script src="Scripts/jquery.signalR-2.2.0.js"></script>
    <script src="/signalr/hubs"></script>
    <script>
        $(function () {
            var moveShapeHub = $.connection.myHub,
                $shape = $("#shape"),
                // Send a maximum of 10 messages per second
                // (mouse movements trigger a lot of messages)
                messageFrequency = 10,
                // Determine how often to send messages in
                // time to abide by the messageFrequency
                updateRate = 1000 / messageFrequency,
                shapeModel = {
                    left: 0,
                    top: 0
                },
                moved = false;
            moveShapeHub.client.updateShape = function (model) {
                shapeModel = model;
                $shape.css({ left: model.left, top: model.top });
            };
            $.connection.hub.start().done(function () {
                $shape.draggable({
                    drag: function () {
                        shapeModel = $shape.offset();
                        moved = true;
                        moveShapeHub.client.updateShape = function (model) {
                            shapeModel = model;
                            // Gradually move the shape towards the new location (interpolate)
                            // The updateRate is used as the duration because by the time 
                            // we get to the next location we want to be at the "last" location
                            // We also clear the animation queue so that we start a new 
                            // animation and don't lag behind.
                            $shape.animate(shapeModel, { duration: updateRate, queue: false });
                    }
                });
                // Start the client side server update interval
                setInterval(updateServerModel, updateRate);
            });
            function updateServerModel() {
                // Only update server if we have a new movement
                if (moved) {
                    moveShapeHub.server.updateModel(shapeModel);
                    moved = false;
                }
            }
        });
    </script>

    <div id="shape" />
</body>
</html>

参考

 

原文地址:https://www.codeproject.com/Tips/880963/Introduction-to-SignalR

Guess you like

Origin blog.csdn.net/mzl87/article/details/91377304