1、编写前端需要同步的数据代码<div class="leftBoxbottom" style="margin-top: 20px;"> <a onclick="moreData('jyj_gy')" href="javascript:void(0)"><h3 class="leftBoxtitle">加药间 :</h3></a> <div class="contentareas"> <p class="boxitem"> <span class="boxitem_title" style="padding-right: 2px;">乙酸钠储池A液位:</span> <span> <span class="inwalter" id="M_LIT88901A_EU">读取中...</span> <span>m</span> </span> </p> <p class="boxitem"> <span class="boxitem_title" style="padding-right: 2px;">乙酸钠储池B液位:</span> <span> <span class="inwalter" id="M_LIT88901B_EU">读取中...</span> <span>m</span> </span> </p> <p class="boxitem"> <span class="boxitem_title" style="padding-right: 2px;">PAC储池A液位:</span> <span class="inwalter" id="M_LIT82601A_EU">读取中...</span> <span>m</span> </p> <p class="boxitem"> <span class="boxitem_title" style="padding-right: 2px;">PAC储池B液位:</span> <span> <span class="inwalter" id="M_LIT82601B_EU">读取中...</span> <span>m</span> </span> </p> <p class="boxitem"> <span class="boxitem_title" style="padding-right: 2px;">PAC投加量流量:</span> <span> <span class="inwalter" id="PACLDOSE_FLOW">读取中...</span> <span>m³/h</span> </span> </p> <p class="boxitem"> <span class="boxitem_title" style="padding-right: 2px;">乙酸钠溶液投加流量:</span> <span class="inwalter" id="CH3OONADOSE_FLOW">读取中...</span> <span>m³/h</span> </p> </div> </div>
2、编写js代码<script type="text/javascript"> $(function () { WebSocketSet("getdata"); }) var ws;var re = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 //判断正整数 /^[1-9]+[0-9]*]*$/function WebSocketSet(x, callBack) { if (!callBack) { callBack = function (rs) { var data = JSON.parse(rs); //console.log("根本", data) //添加更新时间 var updatetime = data[0].UpdateTime; $("#updatetime").html(updatetime); $.each(data, function (index, item) { getdatas(item); }); setTimeout(function () { SendMessage(x); }, 30*1000); } } ws = new WebSocket("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!") };};function SendMessage(x) { if (ws.readyState == WebSocket.OPEN) { ws.send(x); } else { alert("Connection is Closed!"); }}function getdatas(item){ item.id = item.id + ""; var datastring; $("#" + item.id).html(datastring)} </script>
3、编写后台代码public string Get(string indexName) { using (Models.dbEntities db = new Models.dbEntities()) { return GetDataJson(db, indexName); } } private async Task ProcessWSChat(AspNetWebSocketContext arg) { using (Models.Entities db = new Models.Entities()) { WebSocket socket = arg.WebSocket; string Receivemessage = null, returnMessage = null; ArraySegment<byte> buffer; try { while (true) { buffer = new ArraySegment<byte>(new byte[1024]); WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None); if (socket.State == WebSocketState.Open) { Receivemessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count); if (Receivemessage.Equals("0000")) { throw new Exception("关闭连接成功"); } returnMessage = GetDataJson(db, Receivemessage); buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(returnMessage)); await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } else { db.Dispose(); break; } //Thread.Sleep(1000); } } catch (Exception e) { db.Dispose(); } } }private string GetDataJson(Models.Entities db, string indexName) { try { string[] keyArr = null; switch (indexName) { case "getdata": keyArr = new string[] { "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: return null; } return db.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 (Exception e) { throw new Exception(e.Message); } }其中keyArr的数组字符串和前台定义的编号对应
4、定义WebApiConfigpublic static void Register(HttpConfiguration config) config.Routes.MapHttpRoute( name: "websocket", routeTemplate: "API/{controller}/{action}", defaults: new { id = RouteParameter.Optional } );}
5、效果,实时推送数据