標籤:
一、簡介
在Asp.net MVC實現的Comet推送的原理很簡單。
伺服器端:接收到伺服器發送的AJAX請求,伺服器端並不返回,而是將其Hold住,待到有東西要通知用戶端時,才將這個請求返回。
用戶端:請求非同步Action,當接收到一個返回時,立即又再發送一個。
缺點:會長期佔用一個Asp.net處理線程。但相比於輪詢,其節省了頻寬。
樣本:
建立一個Controller如下:
//Comet伺服器推送控制器(需設定NoAsyncTimeout,防止長時間請求掛起逾時錯誤) [NoAsyncTimeout, SessionState(SessionStateBehavior.ReadOnly)] public class CometController : AsyncController //需要繼承自非同步AsyncController { /// <summary> /// 非同步方法呼叫,處理用戶端發起的請求 /// </summary> public void IndexAsync() { AsyncManager.OutstandingOperations.Increment(); AsyncManager.Parameters["info"] = "怎麼了"; AsyncManager.OutstandingOperations.Decrement(); } /// <summary> /// 當非同步線程完成時向用戶端發送響應 /// </summary> /// <param name="token">資料封裝對象</param> /// <returns></returns> public ActionResult IndexCompleted(string info) { return Json(info, JsonRequestBehavior.AllowGet); } }
隨便找一個頁面,通過AJAX請求這一個非同步Action:
<html><head> <title>AJAX測試</title> <script src="/Content/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $(function () { getCometServerPush(); }) function getCometServerPush() { $.ajax({ cache: false, url: ‘/Comet/Index‘, success: function (data) { $("#info").html(data); getCometServerPush(); } }); } </script></head><body> <div id="info"></div></body></html>
上面的樣本,如果你在Action上下一個斷點,會不停的看到斷點在迴圈。說明非同步用戶端不停地在推送。當然這個樣本僅僅是說明推送的原理。
二、應用
應用:監控伺服器上的一個txt檔案,當有變化時,推送內容到用戶端。
//Comet伺服器推送控制器(需設定NoAsyncTimeout,防止長時間請求掛起逾時錯誤) [NoAsyncTimeout, SessionState(SessionStateBehavior.ReadOnly)] public class CometController : AsyncController //需要繼承自非同步AsyncController { /// <summary> /// 非同步方法呼叫,處理用戶端發起的請求 /// </summary> public void IndexAsync() { AsyncManager.OutstandingOperations.Increment(); FileSystemWatcher FSW = new FileSystemWatcher(); FSW.Filter = "123.txt"; //僅僅監控123.txt檔案 FSW.Path = Server.MapPath(@"/"); //設定監控路徑 FSW.EnableRaisingEvents = true; //啟動監控 //FileSystemWatcher暫時有個多次觸發的問題,但與本推送樣本無關,故不解決 FSW.Changed += (object source, FileSystemEventArgs e) => { AsyncManager.Parameters["info"] = System.IO.File.ReadAllText(Server.MapPath(@"/123.txt"),System.Text.Encoding.Default); ; AsyncManager.OutstandingOperations.Decrement(); }; } /// <summary> /// 當非同步線程完成時向用戶端發送響應 /// </summary> /// <param name="token">資料封裝對象</param> /// <returns></returns> public ActionResult IndexCompleted(string info) { return Json(info, JsonRequestBehavior.AllowGet); } }
更多流逼的功能,留著讀者自由發揮。
Asp.net MVC Comet推送