頁面間隔半秒鐘更新時間 Asp.net使用Comet開發http長連線示例分享

NO IMAGE

好處:1.和AJAX輪詢比起來 節省資源,並且延遲小, 2.和webSocket比起來,適用的場景比較廣泛。

1.先建立一個Asp.net MVC的空專案

新增一個控制器  (同樣的程式碼在Asp.net WebForm中也是可以使用的)

複製程式碼 程式碼如下:
public class CometController : Controller
    {
        public ActionResult Test()
        {
            Response.Buffer = false;
            while (true)
            {
                Response.Write(DateTime.Now.ToString(“yyyy-MM-dd HH:mm:ss FFF”) “|”);
                Thread.Sleep(500);
            }
            //跑不到這裡的
            return Content(“”);
        }
    }
}

2.再興建一個控制器和View 用於顯示HTML

複製程式碼 程式碼如下:
public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

    }

View的程式碼比較重要

複製程式碼 程式碼如下:
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
    <script type=”text/javascript” src=”http://code.jquery.com/jquery-1.7.1.min.js”></script>
    <script language=”javascript”>
        var req = false;
        var lastDelimiterPosition = -1;

        $(document).ready(function () {
            getData();
        });

        function getData() {
            loadXMLDoc(“/Comet/Test”);
        }

        //新建一個XHR
function createRequest() {
            if (window.XMLHttpRequest && !(window.ActiveXObject)) {
                try {
                    req = new XMLHttpRequest();
                } catch (e) {
                    req = false;
                }        // branch for IE/Windows ActiveX version  
            } else if (window.ActiveXObject) {
                try { req = new ActiveXObject(“Msxml2.XMLHTTP”); } catch (e) {
                    try {
                        req = new ActiveXObject(“Microsoft.XMLHTTP”);
                    } catch (e) {
                        req = false;
                    }
                }
            }
        }

        //發起請求
function loadXMLDoc(url) {
            try {
                if (req) {
                    req.abort();
                    req = false;
                }
                createRequest();
                if (req) {
                    req.onreadystatechange = processReqChange;
                    req.open(“GET”, url, true);
                    req.send(“”);
                } else {
                    alert(‘unable to create request’);
                }
            } catch (e) { alert(e.message); }
        }

        //檢查狀態
function processReqChange() {
            if (req.readyState == 3) {
                try {
                    ProcessInput(req.responseText);
                    if (req.responseText.length > 3000) {
                        lastDelimiterPosition = -1; getData();
                    }
                }
                catch (e) {
                    alert(e.message);
                }
            }
        }

        //拆分字串
function ProcessInput(input) {
            var text = input;
            var nextDelimiter = text.indexOf(‘|’, lastDelimiterPosition 1);
            if (nextDelimiter != -1) {
                var timeStamp = text.substring(nextDelimiter 1);
                if (timeStamp.length > 0) {
                    lastDelimiterPosition = nextDelimiter;
                    ProcessTime(timeStamp);
                }
            }
        }

        //輸出 或者觸發什麼事件
function ProcessTime(time) {
            document.getElementById(‘div1’).innerHTML = time;
        }
    </script>
</head>
<body>
    <div>
        <div id=”div1″>
        </div>
        <div id=”div2″>
        </div>
    </div>
</body>
</html>

3.最終效果為:

頁面上顯示一個時間,每隔半秒鐘更新一次

當然,拿到內容以後,其實你想做什麼就做什麼。。。更新DOM也好,執行js也好, (還好有eval這個方法~~)

4.這個例子只是基於非同步Javascript的一個實現,

實際上還可以通過<iframe> 和 <script>這兩個標籤做實現,特別是script標籤可以訪問和執行跨域的javascript

您可能感興趣的文章:

詳解Tomcat如何實現CometJavaScript資料推送Comet技術詳解使用Java實現類似Comet風格的web appBitComet 0.89 去廣告簡潔優化版 下載jQuery Ajax全解析jquery實現ajax提交form表單的方法總結jquery ajax例子返回值詳解基於JQuery框架的AJAX例項程式碼完美解決AJAX跨域問題Ajax和Comet技術總結