




已阅读5页,还剩12页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
A SignalR 实现服务端消息推送到Web端 之前的文章介绍过A SignalR, ASP .NET SignalR是一个ASP .NET 下的类库,可以在ASP .NET 的Web项目中实现实时通信. 今天我们来实现服务端消息推送到Web端, 首先回顾一下它抽象层次图是这样的:实际上 A SignalR 2 实现 服务端消息推送到Web端, 更加简单. 为了获取更好的可伸缩性, 我们引入消息队列, 看如下基本流程图:消息队列MQ监听, 在Web site 服务端一收到消息,马上通过Signalr 推送广播到客户端. 创建ASP.NET MVC WEB APP, 从NuGet 安装SignalR 2.12Install-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); / / Registers the mq listen and hubs. / public static void RegisterMQListenAndHubs() var activemq = Megadotnet.MessageMQ.Adapter.ActiveMQListenAdapter.Instance(MQConfig.MQIpAddress, MQConfig.QueueDestination); activemq.MQListener += m = log.InfoFormat(从MQ收到消息0, m.MSG_CONTENT); GlobalHost.ConnectionManager.GetHubContext().Clients.All.receive(m); ; activemq.ReceviceListener(); 上面有一句关键代码GlobalHost.ConnectionManager.GetHubContext().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, 用于Owinassembly: 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 具体与SignalR.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 lidata-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代码与服务端有通信, 具体看如下图: 在Index.cshtml, 我们需要引用SignalR客户端JS, 放置hubs, 这里我们使用了jsrender, easyui.js 来呈现推送的消息.model dynamicsection Scripts Scripts.Render(/Scripts/project.js) $(document).ready(function () var app = new App(); ); Feed Message Id MSG_CONTENT 上代码服务端引用js的Script.Render, 需要在BundleConfig.cs中加入以下代码: bundles.Add(new ScriptBundle(/Scripts/project.js) .IncludeDirectory(/Scripts/Project, *.js, false);同时我们构建一个WebAPI来发送需要推送的消息, 片断代码: / / SendMessage / / The messagemodel. / HttpPost public IHttpActionResult SendMessage(PushMessageModel messagemodel) return SendToServer(messagemodel); / / Sends to server. / / The messagemodel. / 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); / / 发送消息 / / / public bool SendMessage(PushMessageModel messagemodel) var activemq = new ActiveMQAdapter(MQConfig.MQIpAddress, MQConfig.QueueDestination); return activemq.SendMessage(messagemodel)0; 如果您需要运行DEMO程序,需要构建基于ActiveMQ的消息队列, 运行效果是这样的, 我们在一个静态html中, 发送一个ajax到webapi服务端, 发送后另一个website网站收到后, 列表更新, 并在右下角弹出框IE的控制台输出:HTML1300: Navigation occurred.File: Index11: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 doesnt support SSE.11:05:25 GMT+0800 (China Standard Time) SignalR: Binding to iframes 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.InitConnected!11:05:25 GMT+0800 (China Standard Time) SignalR: Invoked feedhub.Init11: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
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 配电考试题及答案
- 机设考试题及答案
- 中级财务会计(上)(山东联盟)知到智慧树答案
- 会计继续教育“行政单位会计制度”考试试题及答案
- 中外设计史知到智慧树答案
- 事业单位考试题公基真题及答案
- 2025房产电商团购合作未来市场趋势预测及应对策略协议
- 2025版房产代理销售合同范本:海外房产投资顾问
- 2025版高科技产业园区土地及房屋租赁合同模板
- 2025年度家用电器分期付款标准合同范本
- 公安科技信息化课件
- 桥梁工程支架浇筑连续箱梁的施工监理实施细则
- 2025年国家药品监督管理局直属单位招聘126人笔试模拟试题及参考答案详解
- 2025年医疗器械经营企业法律法规培训考试(含答案)
- 2025年部编版新教材语文九年级上册教学计划(含进度表)
- 2025年云南省中考数学真题含答案
- 留疆战士考试题库及答案
- 中小学老师管理办法
- 食堂工作人员食品安全培训
- T∕CITS 146-2024 尿液有形成分名称与结果报告规范化指南
- 金属封闭母线
评论
0/150
提交评论