Asp.net MVC Comet推送

來源:互聯網
上載者:User

標籤:

一、簡介

  在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推送

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.