标签:
1.连续找了几天解决ajax轮询在用户量多的时候卡死浏览器的方案,comet、SignalR等等。都没有得到满意的解决,最后还是用了websocket临时解决了
2.解决方案,还是需要用到.net framework 4.5版本下 IHttphandler
1 public void ProcessRequest(HttpContext context) 2 { 3 if (context.IsWebSocketRequest) 4 { 5 context.AcceptWebSocketRequest(DoRespond); 6 } 7 } 8 private async Task DoRespond(AspNetWebSocketContext context) 9 { 10 System.Net.WebSockets.WebSocket socket = context.WebSocket; 11 while (true) 12 { 13 ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]); 14 WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None); 15 if (socket.State == WebSocketState.Open) 16 { 17 string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count); 18 userMessage = "测试消息 : " + userMessage ; 19 buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage)); 20 await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); 21 } 22 else 23 { 24 break; 25 } 26 } 27 }
3.界面端,就可以用手动调用,或者结合一个js计时器 即可实现,服务端不断推送消息过来,打开Chrome调试 并不会看到有向后台发起的请求。测试相同用户数量后,比以前的ajax轮询 的效率高了很多。 还需研究 用更简便、科学的方式解决
1 var socket; 2 3 $(document).ready(function () { 4 if (!Modernizr.websockets) 5 { 6 alert("This browser does not support web sockets"); 7 } 8 9 socket = new WebSocket("ws://localhost:49464/WebSocketHandler.ashx"); 10 11 socket.addEventListener("open", function (evt) { 12 $("#divHistory").append(‘<h3>Connection Opened with the server.</h3>‘); 13 }, false); 14 15 socket.addEventListener("close", function (evt) { 16 $("#divHistory").append(‘<h3>Connection was closed. :‘ + evt.reason + ‘</h3>‘); 17 }, false); 18 19 socket.addEventListener("message", function (evt) { 20 $("#divHistory").append(‘<h3>‘ + evt.data + ‘</h3>‘); 21 }, false); 22 23 socket.addEventListener("error", function (evt) { 24 alert(‘Error : ‘ + evt.message); 25 }, false); 26 var rtimer; 27 function loadRiskWindow() { 28 //rtimer = window.setInterval("LoadMyFundsWork()", 3000); 29 }
标签:
原文地址:http://www.cnblogs.com/zfthm/p/4537133.html