SignalR,Angular JS 以及 ASP.NET MVC 实时通信

来源:互联网 发布:数据库原理与应用的ppt 编辑:程序博客网 时间:2024/06/17 02:51

SignalR,Angular JS 以及 ASP.NET MVC 实时通信

作者:Yasser Mmtaz

日期:2015/3/19

原文地址:http://www.codeproject.com/Tips/888366/SignalR-Angular-JS-and-ASP-NET-MVC-Real-Time-Commu 

概述:基于ASP.NET MVC 和C#,使用SignalR和Angular JS 开发实时通信应用程序。

简介:

在本文中,我将解释如何基于ASP.NET MVC 和C#,使用SignalR和Angular JS 开发实时通信应用程序。我曾遇到过这样一个难题:不同的CRS(Customer Service Representation ,客户服务代表)可以更新提交同一个客户的信息,如果他们在同一时间提交信息,那么其中一个CRS提交的信息,可能会覆盖其他CRS提交的信息。CRS建议,当任何CRS更新信息的时候,对所有处在编辑界面的CRS即时发出相关通知。

我使用SignalR、Angular JS 和toaster.js,完成了在客户端显示通知信息的功能。如果想了解更多关于SignalR,请阅读链接: http://signalr.net   。下面是整个完成整个开发的步骤,和相应的部分代码。


准备开始

1-首先,你需要保证电脑上安装了SignalR,如果没有,可以在NuGet Package(Visual Studio中一般有的)中输入以下命令安装:

Install-Package Microsoft.AspNet.SignalR.Sample

2-然后,确认在你的网站解决方案中包含了以下JS文件,如果没有,你可以在相应官网上下载:

angular.js

jquery.singalR-x.x.x.js

toaster.js

3-创建一个新的SignalR hub 类 BroadcastMessageHub.cs,然后复制以下代码(如果想了解更多关于SignalR 和ASP.NET MVC ,请阅读链接:http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc ):

<span style="font-size:14px;">using Microsoft.AspNet.SignalR;using Microsoft.AspNet.SignalR.Hubs;namespace JobTracker{  [HubName("chat")]  public class MultiUserHub : Hub   {     public void SendMessage(string message)      {        Clients.All.newMessage(message);      }  }}</span>

4-创建 Startup.cs 类,然后复制以下代码:

<span style="font-size:14px;">using Microsoft.Owin;using Owin;[assembly: OwinStartup(typeof(JobTracker.Startup))]namespace JobTracker {   public class Startup    {      public void Configuration(IAppBuilder app)       {        app.MapSignalR();       }    }  }</span>

5-服务器端代码和配置完成了,现在我们来构建用户端,创建两个JS文件:app.js和mainCtrl.js。你可以根据自己喜好,随意命名这两个js文件,app.js拥有Angular组件定义和与服务器端通信的函数。


App.js

<span style="font-size:14px;">//toaster is added as dependency that will show message in attractive warning message box, to read//more about toaster.js please follow link: <a href="http://codeseven.github.io/toastr/demo.html">http://codeseven.github.io/toastr/demo.html</a>(function () {    angular.module('app', ['toaster']);$(function () {  $.connection.hub.logging = true;  $.connection.hub.start(); });$.connection.hub.error(function (err) {  console.log('An error occurred: ' + err); }); angular.module('app').value('chat', $.connection.chat);})();</span>
mainCtrl.js

<span style="font-size:14px;">//$http service is used to get logged on user information from controller action, you can use $resource //service to get info through ASP.NET Web API.//chat and toaster are dependencies defined in angular module to send message to all user and show//it in toaster "warning" dialog box"use strict";angular.module('app').controller('mainCtrl', function ($scope, $http, chat, toaster) { $scope.messages = []; $http.get("GetLoginUserID").then(function (response) { $scope.LogonUserID = response.data;});$scope.sendMessage = function () { chat.server.sendMessage($scope.LogonUserID.data +' Just modified records, please refresh page to get latest!'); $scope.newMessage = "";};chat.client.newMessage = function onNewMessage(message) { toaster.pop('warning', "Please read message!", message); $scope.messages.push({ message: message }); $scope.$apply(); console.log(message); };});</span>

6-以上两个js文件创建完成之后,如果你需要使用“消息广播功能”,请确认你在ASP.NET页面中或者MVC view 中引用以下的js文件。

  •  jquery.singalR-x.x.x.js
  • <script src='/signalr/hubs'></script> for dynamically generating scripts, you can check generated script through developer tool.
  • angular.js
  • toaster.js
  • app.js
  • mainCtrl,.js

7-你需要为toaster container添加以下代码,设置消息框的timeout参数,参数单位为毫秒:

<span style="font-size:14px;"><toaster-container toaster-options="{'time-out': 5000}"></toaster-container></span>

8-最后一步就是将消息事件绑定到需要的控件上,我将其绑定在提交按钮上,发送消息的方法sendMessage()定义在mainCtrl.js中:

<span style="font-size:14px;"><input id="btnSave" ng-click="sendMessage()" type="submit" value="Save" /></span>

9-最后效果如下:

"If there are two users UserA and UserB are on same edit screen, as soon UserA will submit btnSave button, toaster warning dialog box "UserA just modified record, please refresh page to get latest!" would be displayed on top right corner of screen on both UserA and UserB screens. The same functionality should be working forn number of logged on users.


License

This article, along with any associated source code and files, is licensed underThe Code Project Open License (CPOL)


0 0
原创粉丝点击