本文實例講述了ASP.NET中ServerPush用法。分享給大家供大家參考。具體分析如下:
什麼是ServerPush,服務器向客戶端“推送“,其實就是”長連接“
只有浏覽器請求服務器端,服務器端才給浏覽器響應數據,不會主動向浏覽器推送數據,這是一種安全考慮,也是提高服務器的性能考慮,如果服務器向浏覽器主動推送數據,就要用到ServerPush等技術模擬實現。
舉個例子:
通過兩個頁面互相發送消息實現,消息放到數據庫。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 /// <summary> /// ServerPush1 的摘要說明 /// </summary> public class ServerPush1 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; string action = context.Request["action"]; if (action == "send")//發送 { string me = context.Request["me"]; string toUserName = context.Request["toUserName"]; string msg = context.Request["msg"]; SQLHpler.ExecuteNonQuery("INSERT INTO T_Msgs(FromUserName,ToUserName,Msg) VALUES(@FromUserName,@ToUserName,@Msg)", new SqlParameter("@FromUserName", me), new SqlParameter("@ToUserName", toUserName), new SqlParameter("@Msg", msg)); context.Response.Write(new JavaScriptSerializer().Serialize(new { Status = "ok" })); } else if (action == "receive") //登陸,並持續查詢、接收對方發過來的數據 { //做一個簡單的例子,以ServerPush1.ashx?me=sean //請把發給sean的消息發給我一條 string me = context.Request["me"]; while (true) { DataTable dt = SQLHpler.ExecuteQuery("SELECT TOP 1 * FROM T_Msgs WHERE ToUserName=@ToUserName",new SqlParameter("@ToUserName", me)); if (dt.Rows.Count <= 0) { Thread.Sleep(500);//沒找到,休息500ms再查詢,這樣避免對數據庫的查詢壓力,和占用WEB服務器CPU資源 continue;//下一次while } else { DataRow row = dt.Rows[0]; long id = (long)row["Id"]; string fromUserName = (string)row["FromUserName"]; string msg = (string)row["Msg"]; //查詢完之後要刪除消息,否則會出現死循環,不停的給頁面輸出同一個消息 SQLHpler.ExecuteNonQuery("DELETE FROM T_Msgs WHERE Id=@Id",new SqlParameter("@Id",id)); //創建一個匿名對象,將查詢到的數據存到裡面 var data = new { FromUserName = fromUserName, Msg = msg, Id = id }; string json = new JavaScriptSerializer().Serialize(data);//將匿名對象轉換為json context.Response.Write(json);//將請求結果以json格式返回 break; } } } else { throw new Exception("action錯誤"); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script type="text/javascript" src="jquery-1.8.3.min.js"></script> <script type="text/javascript"> var rev = function () { var mine = $('#me').val(); $.ajax({ type: 'post', url: 'serverPush1.ashx', data: { action: 'receive', me: mine },//傳給serverPush.ashx根據me查找發給me的消息 success: function (data) { $('#ulMsg').append($('<li>' + data.FromUserName + '對我說:' + data.Msg + '</li>')); rev();//收到消息後再向服務器請求數據,再給我一條消息 }, error: function () { rev(); //哪怕網絡請求失敗(比如用戶網絡故障),也再次發送請求 } }); }; $(function () { //發送 $('#btnSend').click(function () { var myName = $('#me').val(); var toUserName = $('#toUserName').val(); var msg = $('#msgContext').val(); $.ajax({ type: 'post', url: 'serverPush1.ashx', data: { action: 'send', me: myName, toUserName: toUserName, msg: msg },//根據用戶輸入的信息,傳到服務端ServerPush.ashx進行插入操作 success: function (data) { if (data.Status == 'ok') {//如果發送成功, $('#ulMsg').append($('<li>我對' + toUserName + '說:' + msg + '</li>')); $('#msgContext').val(''); } else { alert('發送出錯,返回報文無法識別'); } }, error: function () { alert('發送出錯'); } }); }); //登陸,接收數據 $('#btnLogin').click(function () { rev(); $(this).attr("disabled", "disabled"); }); /* $('#btnLogin').click(function () {//接收 var mine = $('#me').val(); $.ajax({ type: 'post', url: 'serverPush1.ashx', data: { action: 'receive', me: mine }, //傳給serverPush.ashx根據me查找發給me的消息 success