养生 装修 购物 美食 感冒 便秘 营销 加盟 小吃 火锅 管理 创业 搭配 减肥 培训 旅游

asp.net mvc +websocket 推送数据

时间:2024-10-21 06:37:14

主要是基于html5的websocket进行后台数据推送更新,后台使用asp.netmvc来处理业务数据逻辑,实现数据随时更新推送,此外,ajax轮询和websocket的获取数据同步的方法比较这里就不列出。

工具/原料

vs2013,iis7.5

笔记本

方法/步骤

1、编写前端需要同步的数据代码<divclass="leftBo垓矗梅吒xbottom"style="margin-t泠贾高框op:20px;"><aonclick="moreData('jyj_gy')"href="javascript:void(0)"><h3class="leftBoxtitle">加药间&nbsp;:</h3></a><divclass="contentareas"><pclass="boxitem"><spanclass="boxitem_title"style="padding-right:2px;">乙酸钠储池A液位:</span><span><spanclass="inwalter"id="M_LIT88901A_EU">读取中...</span><span>m</span></span></p><pclass="boxitem"><spanclass="boxitem_title"style="padding-right:2px;">乙酸钠储池B液位:</span><span><spanclass="inwalter"id="M_LIT88901B_EU">读取中...</span><span>m</span></span></p><pclass="boxitem"><spanclass="boxitem_title"style="padding-right:2px;">PAC储池A液位:</span><spanclass="inwalter"id="M_LIT82601A_EU">读取中...</span><span>m</span></p><pclass="boxitem"><spanclass="boxitem_title"style="padding-right:2px;">PAC储池B液位:</span><span><spanclass="inwalter"id="M_LIT82601B_EU">读取中...</span><span>m</span></span></p><pclass="boxitem"><spanclass="boxitem_title"style="padding-right:2px;">PAC投加量流量:</span><span><spanclass="inwalter"id="PACLDOSE_FLOW">读取中...</span><span>m³/h</span></span></p><pclass="boxitem"><spanclass="boxitem_title"style="padding-right:2px;">乙酸钠溶液投加流量:</span><spanclass="inwalter"id="CH3OONADOSE_FLOW">读取中...</span><span>m³/h</span></p></div></div>

2、编写js代码<scripttype="text/javascript">$(function(){WebSocketSet("getdata");})varws;varre=/^[0-9]+.?[0-9]*$/;//判断字符串是否为数字//判断正整数/^[1-9]+[0-9]*]*$/functionWebSocketSet(x,callBack){if(!callBack){callBack=function(rs){vardata=JSON.parse(rs);//console.log("根本",data)//添加更新时间varupdatetime=data[0].UpdateTime;$("#updatetime").html(updatetime);$.each(data,function(index,item){getdatas(item);});setTimeout(function(){SendMessage(x);},30*1000);}}ws=newWebSocket("ws://"+window.location.hostname+":"+window.location.port+"/webapi/WebSocket");ws.onopen=function(){SendMessage(x);};ws.onmessage=function(data){callBack(data.data);};ws.onerror=function(error){alert("链接错误,错误信息如下:"+error.data)};ws.onclose=function(){//alert("Disconnected!")};};functionSendMessage(x){if(ws.readyState==WebSocket.OPEN){ws.send(x);}else{alert("ConnectionisClosed!");}}functiongetdatas(item){item.id=item.id+"";vardatastring;$("#"+item.id).html(datastring)}</script>

3、编写后台代码publicstringGet(stringindexNam娣定撰钠e){us足毂忍珩ing(Models.dbEntitiesdb=newModels.dbEntities()){returnGetDataJson(db,indexName);}}privateasyncTaskProcessWSChat(AspNetWebSocketContextarg){using(Models.Entitiesdb=newModels.Entities()){WebSocketsocket=arg.WebSocket;stringReceivemessage=null,returnMessage=null;ArraySegment<byte>buffer;try{while(true){buffer=newArraySegment<byte>(newbyte[1024]);WebSocketReceiveResultresult=awaitsocket.ReceiveAsync(buffer,CancellationToken.None);if(socket.State==WebSocketState.Open){Receivemessage=Encoding.UTF8.GetString(buffer.Array,0,result.Count);if(Receivemessage.Equals("0000")){thrownewException("关闭连接成功");}returnMessage=GetDataJson(db,Receivemessage);buffer=newArraySegment<byte>(Encoding.UTF8.GetBytes(returnMessage));awaitsocket.SendAsync(buffer,WebSocketMessageType.Text,true,CancellationToken.None);}else{db.Dispose();break;}//Thread.Sleep(1000);}}catch(Exceptione){db.Dispose();}}}privatestringGetDataJson(Models.Entitiesdb,stringindexName){try{string[]keyArr=null;switch(indexName){case"getdata":keyArr=newstring[]{"CCPH","CCT","P104_RUNTIME_TTL_HIS","B104_RUNTIME_TTL_HIS","P103_RUNTIME_TTL_HIS","B103_RUNTIME_TTL_HIS","P102_RUNTIME_TTL_HIS","B102_RUNTIME_TTL_HIS","CCB102_F","CCB102_I","P101_RUNTIME_TTL_HIS","B101_RUNTIME_TTL_HIS","CCB101_F","CCB101_I"};break;default:returnnull;}returndb.RealTime.Where(s=>keyArr.Contains(s.Tag)).Select(s=>new{id=s.Tag,s.UpdateTime,Value=s.Value,TagName=s.TagName,s.ExceptionSatus}).ToJson();}catch(Exceptione){thrownewException(e.Message);}}其中keyArr的数组字符串和前台定义的编号对应

4、定义WebApiConfigpublicstaticvoidRegister(HttpConfigurationconfig)config.Routes.MapHttpRoute(name:"websocket",routeTemplate:"API/{controller}/{action}",defaults:new{id=RouteParameter.Optional});}

5、效果,实时推送数据

asp.net mvc +websocket 推送数据

© 一点知识