SignalRについて

ディレクトリ

入門

SignalRとは何ですか?

そして、接続ハブ(ハブ)

アプリケーションの作成

クライアントのサイクルを追加します

サーバーの循環を追加

クライアント側の滑らかなアニメーションに追加します

参照


入門

このヒントではカバーし、Webをアプリケーション環境を使用してSignalRは、クライアントではなくサーバーからデータを要求するクライアントを待っているよりも、利用可能なときに、サーバーはすぐにクライアントに情報をプッシュすることができ、情報のリアルタイム通信を導入しました。

SignalR World Wide Web上のチャットアプリケーションのためには、ダッシュボードやゲームが産業用デスクトップアプリケーションのための非常に便利なだけでなく、非常に重要です。

あなたが使用している場合はAJAXを改善するためのWeb 応答アプリケーションを、そしてSignalRは有用な代替です。

あなたはログイン可能にすることによって、決定することができSignalRの使用されているトランスポート・タイプ:

$.connection.hub.logging = true;

あなたが続く場合は、Webをブラウザのデバッグツールを開くには、あなたのような、わかります「SignalR オープンのWebSocket」ラインなどが挙げられます。

何がSignalRは

一般的には、サーバからクライアントへのより多くのデータを取得する(変更された場合)、あなたが使用する必要がありますHTTPのポーリングGET され、AJAXをやっています。あなたが任意の近くに本物をしたい場合は、常にポーリングする必要があります。代わりに、使用SignalRを、あなたが永続的な接続を持って、クライアントは、サーバがクライアントを呼び出すことができ、サーバーを呼び出すことができます。

したがって、SignalRは、サーバとクライアントの接続は、従来と、耐久性のあるリアルタイム通信、簡素化し、開発者のライブラリであるHTTPの異なるパラダイムを。

お使いのコンピュータが使用している場合のWindows 8 またはWindows Serverの2012 以降および.NET Frameworkの4.5を、そしてSignalRを使用するのWebSocketを、そうでない場合、それが使用するHTML 5 の送信や彗星の送信を。

そして、接続ハブ(ハブ)

クライアントとサーバ間の通信の両方のモデルは、持続的な接続やハブです。

これは、単一の受信者、メッセージのブロードキャストパケット又は端部に接続された送信を示します。

ハブは、永続的な接続である(持続的接続)クライアントとサーバーが互いに直接メソッドを呼び出すことができます層の上に。使用.NETリモート処理、.NET 開発者は、このモデルに精通しているであろう。これは、あなたが強く型付けされたパラメータを渡すことができます。

ときに通信チャネルを介して完全なオブジェクトの送信は、それらが使用するJSONがシリアライズ。

あなたは使用することができますフィドラーを監視方法の他のツールを呼び出すために。

アプリケーションの作成

まず、空の作成ASP.NETのWeb プロジェクトを追加するために右クリックSignalRのためのプロジェクトを確認して、.NET 4.5 またはそれ以降:

選択SignalRを

それとも、単にパッケージマネージャコンソールを入力することができます。

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

次に、と呼ばれるスタートアップアプリケーションに追加されたクラス、クラスのマッピングアプリケーションの起動SignalRのハブ:

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

あなたがいない場合は、次のように追加してくださいSignalRのハブカテゴリを:

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

クライアントが呼び出すことができるのUpdateModelの方法をして、接続されているすべてのクライアントにブロードキャストします。これは、使用してJSON 自動シリアライズを。

今の溶液に加えることによって、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.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

おすすめ

転載: blog.csdn.net/mzl87/article/details/91377304