手机版

ASP .NET MVC4异步聊天室的示例代码

时间:2021-09-03 来源:互联网 编辑:宝哥软件园 浏览:

本文介绍了ASP .NET MVC4异步聊天室的示例代码,分享给大家,具体如下:

类图:

领域层

IChatRoom.cs

使用系统;使用系统。集合。通用;命名空间MvcAsyncChat .域{公共接口IChatRoom { void AddMessage(字符串消息);void AddParticipant(字符串名称);无效的获取消息(日期时间自,ActionIEnumerablestring,DateTime回调);void RemoveParticipant(字符串名称);}} IMessageRepo.cs

使用系统;使用系统。集合。通用;命名空间MvcAsyncChat .域{公共接口IMessageRepo { DateTime Add(字符串消息);ienumerablesting get after(DateTime after);}}ICallbackQueue.cs

使用系统;使用系统。集合。通用;命名空间MvcAsyncChat .域{公共接口ICallbackQueue { void Enqueue(ActionIEnumerablestring,DateTime回调);ienumerablessing,DateTime出列all();ienumerablectionienumerablestring,DateTime出列过期(日期时间过期);}}ChatRoom.cs

使用系统;使用系统。集合。通用;使用系统Linq .使用系统。穿线;使用MvcAsyncChat .上腔静脉综合征命名空间MvcAsyncChat .域{公共类聊天室: IChatRoom { readonly ICallbackQueue callbackQueue;只读IDateTimeSvc datetime VCreadonly IMessageRepo messageRepo;公共聊天室(ICallbackQueue callbackQueue,IDateTimeSvc dateTimeSvc,IMessageRepo messageRepo){ this。callbackQueue=callbackQueue这个。日期时间VC=日期时间VC;this . messageRepo=messageRepo } public void AddMessage(字符串消息){ var timestamp=messageRepo .添加(消息);回调队列中的foreach (var回调)。出列All())回调(新[] { message },时间戳);} public void AddParticipant(字符串名称){ AddMessage(字符串。格式(' {0}已进入房间.',名称));} public void GetMessages(DateTime自,ActionIEnumerablestring,DateTime回调){ var messages=messageRepo .获取自(自);如果(消息计数(0)回调(消息,自);否则回调队列。入队(回调);} public void RemoveParticipant(字符串名称){ AddMessage(字符串格式(“{ 0 }”)离开了房间。名称));} } } InMemMessageRepo.cs

使用系统;使用系统。集合。通用;使用系统Linq .命名空间MvcAsyncChat .域{ emmesagerpo中的public类: imessagerpo { emmesagerpo中的public(){ Messages=new listuplestring,DateTime();}公共IListTuplestring,DateTime Messages { get私有集;}公共日期时间添加(字符串消息){ var timestamp=DateTime .UtcNow消息。添加(新的时间戳,日期时间(消息,时间戳));返回时间戳;} public ienumerablesting get after(DateTime after){ 0返回消息。其中(x=x.Item2自)。选择(x=x .第1项);} }}CallbackQueue.cs

使用系统;使用系统。集合。通用;使用系统Linq .命名空间MvcAsyncChat .域{公共类CallbackQueue : ICallbackQueue {公共CallbackQueue(){ 0回调=new queuetuplecitionienumblestring,DateTime,DateTime();} public queuetuplecitionienumblestring,DateTime,DateTime回调{获取私有集;} public void Enqueue(ActionIEnumerablestring,DateTime回调){回调。入队(新TupleActionIEnumerablestring,DateTime,DateTime(回调,DateTime .UtcNow));} public ienumerablecitionenumeblestring,DateTime出列All() { while(回调。计数0)产生返回回调。出队(.项目1);} public ienumerablecitionenumeblestring,DateTime出列过期(日期时间过期){如果(回调计数==0)收益率中断;定义变量最旧=回调peek();而(回调。最早计数0。项目2=到期){产生返回回调。出队(.项目1);如果(回调。计数0)最旧=回调peek();} } }}RequestModels文件夹实体类

EnterRequest.cs

使用系统;使用系统组件模型.使用系统。组件模型。数据注释;命名空间MvcAsyncChat .请求模型{公共类输入请求{[显示名称('名称)][必需,stringlength(16),regularexpression(@'^[a-za-z0-9_\-]$ ',错误消息='名称必须是字母数字')]公共字符串名称{ get设置;} }}GetMessagesRequest.cs

使用系统;命名空间MvcAsyncChat .请求模型{公共类GetmessagesRequest {公共字符串,自{获取设置;} }}SayRequest.cs

使用系统;使用系统组件模型.使用系统。组件模型。数据注释;命名空间MvcAsyncChat .RequestModels{公共类说出请求{[必选,字符串长度(1024),数据类型(数据类型.多重文本])公共字符串文本{获取设置;} } }响应模型文件夹实体类

GetMessagesResponse.cs

使用系统;使用系统。集合。通用;命名空间MvcAsyncChat .响应模型{公共类getmessages response {公共字符串错误{ get设置;} public IEnumerablestring消息{获取设置;}自{获取设置;} }}SayResponse.cs

使用系统;命名空间MvcAsyncChat .响应模型{公共类say response {公共字符串错误{ get设置;} }}ChatController.cs

使用系统;使用系统。集合。通用;使用系统Linq .使用系统网络.使用系统网络。手动音量调节使用系统网络。Mvc。异步非同步(asynchronous)使用MvcAsyncChat .领域;使用MvcAsyncChat .RequestModels使用MvcAsyncChat .响应模型使用MvcAsyncChat .上腔静脉综合征命名空间MvcAsyncChat .控制器{公共类聊天控制器:异步控制器{ readonly iauthtsvc authSvc只读IChatRoom聊天室;只读IDateTimeSvc datetime VC公共ChatController(IAuthSvc authSvc,IChatRoom chatRoom,IDateTimeSvc datetime VC){ this。authSvc=authSvc聊天室。日期时间VC=日期时间VC;} [ActionName('enter '),HttpGet]公共操作结果ShowEnterForm(){ if(User .身份。IsAuthenticated)返回重定向路径(路径名).房间);返回视图();} [ActionName('enter '),Http set]公共操作结果EnterRoom(Entrequest Entrequest){ if(!ModelState .IsValid)返回视图(EnTERREquEST);authSvc .验证(输入请求.名称);聊天室。添加参与者(输入请求。名称);返回重定向路由(路由名称.房间);} [ActionName('room '),HttpGet,Authorize]公共动作结果showcase(){ return View();} [ActionName('leave '),HttpGet,Authorize]公共操作结果leave room(){ authSvc .unauthenticate();聊天室。移除参与者(用户。身份。姓名);返回重定向路由(路由名称.输入);}[httpset,Authorize]公共操作结果Say(说出请求说出请求){ if(!ModelState .IsValid)返回Json(new SayResponse() { error='该请求无效.'});聊天室。添加消息(用户。'身份。姓名'说:' sayRequest .文本);返回JSON(new SayResponse());} [ActionName('messages ')、HttpPost、Authorize]public void GetMessagesAsync(GetMessagesRequest GetMessagesRequest){ async manager .未完成的操作。增量();if(!ModelState .IsValid) { AsyncManager .参数['错误']='消息请求无效;AsyncManager .参数['自]=null;AsyncManager .参数[' messages ']=null;AsyncManager .未完成的操作。减量();返回;} var自=dateTimeSvc .GetCurrentDateTimeAsUtc();if(!字符串IsNullOrEmpty(getmessages request。后))自=日期时间.解析(getMessagesRequest.since).到世界时();聊天室GetMessages(自,(新消息,时间戳)={ AsyncManager .参数['错误]=null;AsyncManager .参数['自']=时间戳;AsyncManager .参数[' messages ']=新消息;AsyncManager .未完成的操作。减量();});}公共操作结果getmessages已完成(字符串错误,日期时间?自,IEnumerablestring消息){ if(!字符串isnullorhitespace(错误))返回JSON(new get messages response(){ error=error });var data=new get messages response();数据。自=自价值。ToString(' o ');data.messages=消息;返回Json(数据);} }}room.js

定义变量自=' ',errorCount=0,MAX _ ERRORS=6;函数添加消息(消息,类型){ $('#messagesSection td ').追加(' div class=' '(type | | ' ')' ' '消息'/div ')}函数显示错误(错误){添加消息(错误。tostring(),' error ');}函数onSayFailed(XMLHttpRequest,textStatus,Error to){ showError('在说出请求:“文本状态”期间出现意外错误;'错误通过);}函数OnSay(数据){ if(数据。错误){ showError('尝试说出您的消息时出错: '数据。错误);返回;} }函数setSayHandler(){ $(“# Text”).按键(功能(e){ if(e .键码==13){ $(' # SayFOrm ').submit();$('#Text ').val(" ");返回false } });}函数retryGetMessages(){ if(错误计数MAX _ ERRORS){ showError('错误太多。请离开聊天室,重新进入。);} else { setTimeout(function(){ getMessages();},Math.pow(2,错误计数)* 1000);} }函数onmessagefailed(XMLHttpRequest,textStatus,错误通过){ showError('在消息请求: '文本状态'期间出现意外错误;错误通过);retryGetMessages();}函数onMessages(数据,textStatus,XMLHttpRequest){ if(数据。错误){ showError('尝试获取消息: '数据时出错。errorretryGetMessages();返回;}错误计数=0;自=数据。自;for(var n=0;n数据。消息。长度;n)添加消息(数据。消息[n]);setTimeout(函数(){ getMessages();}, 0);}函数getMessages() { $ .ajax({ cache: false,type: 'POST ',dataType: 'json ',url: '/messages ',data: {自: }以来,错误: onMessages失败,成功: Onmessages,超时: 100000 });}聊天视图文件夹

Enter.cshtml

MvcAsyncChat模型。请求模型。输入请求@{视图。标题="输入";布局=' ~/视图/共享/_布局。“cshtml”;} @ section Head { } tr id=' EnTER section ' TD H2[MVC聊天]是使用ASP .NET MVC 3的异步聊天室表tr td class='form-container '字段集图例进入聊天室/图例@使用(Html .begin inform()){ @ Html .EditorForModel()输入类型='提交'值=' Enter '/}/字段集/TD/tr/table/TD/tr @ section PostScript { script $(文档)} .就绪(函数(){ $(“# Name”).焦点();});/script}Room.cshtml

@使用MvcAsyncChat@使用MvcAsyncChat .request models @ model say request @ { View .标题='房间;布局=' ~/视图/共享/_布局。“cshtml”;} @ section Head { script src=' http : @ URl .内容(' ~/脚本/房间。js ')'/script } tr id=' messagesseaction ' TD/TD/trtr id=' actions section ' TD标签为='操作列表'操作:/标签ul id='actionsList' li@Html .RouteLink('离开房间,RouteName .离开)/Li/ul @使用(Ajax .begin information(' say ',new { },new Ajaxooptions(){ onFailure=' OnSayfailed ',OnSuccess='onSay ',HttpMethod='POST ',},new { id=' SayFOrm ' }){ @ Html .editorformmodel()}/TD/tr @ section PostScript { script $(文档)。就绪(函数(){ $('#Text ').attr('占位符','你说:');$('#Text ').焦点();setsayHandler();getMessages();});/script}运行结果如图:

这里写图片描述

这里写图片描述

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

版权声明:ASP .NET MVC4异步聊天室的示例代码是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。