图片 1

上边粗体是 最后大家发的第四条音信控制台的输出.

图片 2

您或然感兴趣的篇章:

        /// <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);

            }

 

        }

 
@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>

       
图片 3

        下边包车型地铁javascript代码与服务端有通讯, 具体看如下图:

仰望对您支付实时Web App有扶助.

而且大家构建1个WebAPI来发送须求推送的音信, 片断代码:

实质上 Asp.net Signal科雷傲 2 达成 服务端信息推送到Web端, 尤其简单.
为了拿走更好的可伸缩性, 大家引入新闻队列, 看如下基本流程图:

图片 4

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

Install-Package Microsoft.AspNet.SignalR

切切实实完毕代码,是这么的,大家扩张2个空的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是1个包裹过的对象. 

    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 具体与SignalRubicon.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();

};

只要您要求周转DEMO程序,须要营造基于ActiveMQ的音讯队列,  
运转效果是那样的, 大家在多个静态html中, 发送三个ajax到webapi服务端, 
发送后

如有想驾驭越来越多软件,系统 IT,公司新闻化 资讯,请关心自小编的微信订阅号:

    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;

        }

    }

        在Index.cshtml,  我们须要引用SignalGL450客户端JS, 放置hubs,
那里大家选取了jsrender,  easyui.js 来显示推送的信息.

上代码服务端引用js的Script.Render, 须求在BundleConfig.cs中投入以下代码:

 

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

图片 5

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

出殡音信到ActiveMQ的根本代码:

作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
正文版权归小编和新浪共有,欢迎转发,但未经小编同意必须保留此段表明,且在篇章页面明显地点给出原著连接,否则保留追究法律权利的义务。
该文章也还要公布在本人的独立博客中-Petter Liu
Blog

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

IE的操纵台出口:

SignalR介绍与Asp.net

图片 6

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’
.

 

 

          以前的篇章介绍过Asp.net
SignalR
,  ASP .NET Signal奥迪Q3是二个ASP .NET
下的类库,能够在ASP .NET 的Web项目中达成实时通讯. 
前日大家来贯彻服务端新闻推送到Web端,   首先回看一下它抽象层次图是那般的:

网站地图xml地图