从前的篇章介绍过Asp.net
SignalR
,  ASP .NET SignalPRADO是1个ASP .NET
下的类库,能够在ASP .NET 的Web项目中实现实时通讯. 
前日大家来兑现服务端音讯推送到Web端,   首先想起一下它抽象层次图是这么的:

图片 1

实则 Asp.net Signal昂Cora 2 实现 服务端音信推送到Web端, 特别简单.
为了拿走更好的可伸缩性, 我们引入音讯队列, 看如下基本流程图:

图片 2

新闻队列MQ监听, 在Web site 服务端一收到消息,登时通过Signalr
推送广播到客户端.  创造ASP.NET MVC WEB APP,  从NuGet 安装SignalGL450 2.12

Install-Package Microsoft.AspNet.SignalR

切实落到实处代码,是这么的,我们扩展一个空的Hub:

    public class FeedHub : Hub

    {

        public void Init()

        {

        }

    }

 

是简容易单的新闻模型, 标题与本文属性:

    [Serializable]

    public class PushMessageModel

    {

        public int Id { get; set; }

        public string MSG_TITLE { get; set; }

        public string MSG_CONTENT { get; set; }

    }

服务端推送具体类,记录日志, 创制新闻队列实例,监听, 等待接受音讯.
那里大家采用的是AcitveMQ的.net客户端.
ActiveMQListenAdapter是二个包裹过的对象. 

    public class MQHubsConfig

    {

        private static ILogger log = new Logger("MQHubsConfig");

 

        /// <summary>

        /// Registers the mq listen and hubs.

        /// </summary>

        public static void RegisterMQListenAndHubs()

        {

            var activemq = Megadotnet.MessageMQ.Adapter.ActiveMQListenAdapter<PushMessageModel>.Instance(MQConfig.MQIpAddress, MQConfig.QueueDestination);

            activemq.MQListener += m =>

            {

                log.InfoFormat("从MQ收到消息{0}", m.MSG_CONTENT);

                GlobalHost.ConnectionManager.GetHubContext<FeedHub>().Clients.All.receive(m);

            };

 

            activemq.ReceviceListener<PushMessageModel>();

        }

    }

地点有一句关键代码GlobalHost.ConnectionManager.GetHubContext<FeedHub>().Clients.All.receive(m); 
那里运用了GetHubContext方法后,直接来播放音讯.

需要在MVCApplication下加载:

    public class MvcApplication : System.Web.HttpApplication

    {

        protected void Application_Start()

        {

            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            RouteConfig.RegisterRoutes(RouteTable.Routes);

            BundleConfig.RegisterBundles(BundleTable.Bundles);

            MQHubsConfig.RegisterMQListenAndHubs();

        }

    }

再正是须要充实一个Starup.cs, 用于Owin

[assembly: OwinStartup(typeof(RealTimeApp.Startup))]

namespace RealTimeApp

{

    public class Startup

    {

        public void Configuration(IAppBuilder app)

        {

            // Any connection or hub wire up and configuration should go here

            app.MapSignalR();

        }

    }

}

接下去是客户端App.js:

function App() {

    var init = function () {

        Feed();

        $.connection.hub.logging = true;

        $.connection.hub.start()

            .done(function() {

                console.log("Connected!");

                $(document).trigger("Connected");

            })

            .fail(function() { console.log("Could not Connect!"); });

    };

 

    init();

};

Feed.js 具体与Signal兰德昂科拉.js通讯, 创制名为receive的function, 与服务端对应

function Feed() {

    var chat = undefined;

 

    var init = function () {

    

        // Reference the auto-generated proxy for the hub.

        chat = $.connection.feedHub;

        // Create a function that the hub can call back to display messages.

        chat.client.receive = function (item) {

            var selector = "ul.feed-list li[data-id=" + item.Id + "]";

            if (!($(selector).length > 0)) {

                $("ul.feed-list").prepend($(".feed-template").render(item));

                $("ul.feed-list li:gt(3)").remove();

            }

 

            $.messager.show({

                title: 'Tips',

                msg: item.MSG_CONTENT,

                showType: 'show'          

            });

 

     

        };

 

        // Start the connection.

        $.connection.hub.start().done(function () {

            chat.server.init();

        });

 

    };

 

    init();

};

        上边的javascript代码与服务端有通讯, 具体看如下图:

       
图片 3

        在Index.cshtml,  大家必要引用SignalSportage客户端JS, 放置hubs,
那里大家利用了jsrender,  easyui.js 来表现推送的音信.

@model dynamic

 

@section Scripts {

<link href="/Content/themes/default/window.css" rel="stylesheet" />

<link href="~/Content/themes/default/progressbar.css" rel="stylesheet" />

<link href="~/Content/themes/default/linkbutton.css" rel="stylesheet" />

<script src="~/Scripts/jquery.signalR-2.1.2.min.js"></script>

<!--Reference the autogenerated SignalR hub script. -->

<script src="~/signalr/hubs"></script>

 

<script src="~/Scripts/jsrender.js"></script>

<script src="~/Scripts/jquery.easyui.min-1.4.1.js"></script>

 

@Scripts.Render("~/Scripts/project.js")

 

    <script type="text/javascript">

        $(document).ready(function () {

            var app = new App();

        });

 

    </script>

}

 

 

<div class="row-fluid">

 

    <div class="span8">

        <div class="widget">

            <div class="widget-header">

                <h2>Feed</h2>

            </div>

            <div class="widget-content">

                <ul class="span12 feed-list"></ul>

            </div>

        </div>

    </div>

</div>

 

<script class="chat-template" type="text/x-jquery-tmpl">

    <li>

        <p>{{>Message}}</p>

    </li>

</script>

 

<script class="feed-template" type="text/x-jquery-tmpl">

    <li data-id="{{>Id}}">

        <div class="row-fluid">

 

            <div class="span8">

                <h3>{{>MSG_CONTENT}}</h3>

            </div>

        </div>

    </li>

</script>

上代码服务端引用js的Script.Render, 必要在BundleConfig.cs中进入以下代码:

          bundles.Add(new ScriptBundle("~/Scripts/project.js")
              .IncludeDirectory("~/Scripts/Project", "*.js", false));

并且我们创设一个WebAPI来发送必要推送的音信, 片断代码:

        /// <summary>

        /// SendMessage

        /// </summary>

        /// <param name="messagemodel">The messagemodel.</param>

        /// <returns></returns>

        [HttpPost]

        public IHttpActionResult SendMessage(PushMessageModel messagemodel)

        {

            return SendToServer(messagemodel);

 

        }

 

        /// <summary>

        /// Sends to server.

        /// </summary>

        /// <param name="messagemodel">The messagemodel.</param>

        /// <returns></returns>

        private IHttpActionResult SendToServer(PushMessageModel messagemodel)

        {

 

            if (ModelState.IsValid)

            {

                if (messageRepository.SendMessage(messagemodel))

                {

                    log.Debug("发送成功!");

                    return Ok();

                }

                else

                {

                    log.ErrorFormat("发送失败!{0}", messagemodel);

                    return Content(HttpStatusCode.ExpectationFailed, new Exception("send message error"));

                }

            }

            else

            {

                log.ErrorFormat("参数验证失败!{0}", messagemodel);

                return Content(HttpStatusCode.BadRequest, ModelState);

            }

 

        }

 

发送消息到ActiveMQ的重庆大学代码:

    public class MessageRepository:IMessageRepository

    {

        private static ILogger log = new Logger("MessageRepository");

 

        /// <summary>

        /// 发送消息

        /// </summary>

        /// <param name="messagemodel"></param>

        /// <returns></returns>

        public bool SendMessage(PushMessageModel messagemodel)

        {

          var activemq = new ActiveMQAdapter<PushMessageModel>(MQConfig.MQIpAddress, MQConfig.QueueDestination);

          return activemq.SendMessage<PushMessageModel>(messagemodel)>0;

        }

    }

 

万一您需求周转DEMO程序,需求构建基于ActiveMQ的新闻队列,  
运转效果是这样的, 大家在贰个静态html中, 发送二个ajax到webapi服务端, 
发送后

图片 4

另1个website网站收到后, 列表更新, 并在右下角弹出框

图片 5

IE的控制台出口:

HTML1300: Navigation occurred.
File: Index
[11:05:25 GMT+0800 (China Standard Time)] SignalR: Client subscribed
to hub ‘feedhub’.
[11:05:25 GMT+0800 (China Standard Time)] SignalR: Negotiating with
‘/signalr/negotiate?clientProtocol=1.4&connectionData=%5B%7B%22name%22%3A%22feedhub%22%7D%5D’.
[11:05:25 GMT+0800 (China Standard Time)] SignalR: This browser
doesn’t support SSE.
[11:05:25 GMT+0800 (China Standard Time)] SignalR: Binding to iframe’s
load event.
[11:05:25 GMT+0800 (China Standard Time)] SignalR: Iframe transport
started.
[11:05:25 GMT+0800 (China Standard Time)] SignalR: foreverFrame
transport selected. Initiating start request.
[11:05:25 GMT+0800 (China Standard Time)] SignalR: The start request
succeeded. Transitioning to the connected state.
[11:05:25 GMT+0800 (China Standard Time)] SignalR: Now monitoring keep
alive with a warning timeout of 13333.333333333332 and a connection lost
timeout of 20000.
[11:05:25 GMT+0800 (China Standard Time)] SignalR: Invoking
feedhub.Init
Connected!
[11:05:25 GMT+0800 (China Standard Time)] SignalR: Invoked
feedhub.Init
[11:07:12 GMT+0800 (China Standard Time)] SignalR: Triggering client
hub event ‘receive’ on hub ‘FeedHub’.
[11:07:18 GMT+0800 (China Standard Time)] SignalR: Triggering client
hub event ‘receive’ on hub ‘FeedHub’.
[11:07:32 GMT+0800 (China Standard Time)] SignalR: Triggering client
hub event ‘receive’ on hub ‘FeedHub’.
[11:07:51 GMT+0800 (China Standard Time)] SignalR: Triggering client
hub event ‘receive’ on hub ‘FeedHub’.
[11:09:25 GMT+0800 (China Standard Time)] SignalR: Triggering client
hub event ‘receive’ on hub ‘FeedHub’
.

地点粗体是 最终我们发的第4条音信控制台的输出.

 

好了,到那儿, 由于篇幅有限, 示例代码没有任何突显,
能够在那时下载
必要安装ActiveMQ

 

指望对你支付实时Web App有帮助.

你可能感兴趣的篇章:

SignalR介绍与Asp.net

如有想打听更加多软件,系统 IT,集团音讯化 资源新闻,请关怀自身的微信订阅号:

图片 6

作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归笔者和果壳网共有,欢迎转载,但未经小编同意必须保留此段注脚,且在小说页面显著地方给出原作连接,不然保留追究法律权利的义务。
该文章也同时发布在本身的独自博客中-Petter Liu
Blog

网站地图xml地图