標籤:stat one url 沒有 help alert string osc 響應
簡單描述:
comet是用ajax實現的伺服器推送,有兩種實現comet的方式,長輪詢和流,這裡只實現長輪詢。
長輪詢的過程:頁面發起一個伺服器請求,然後伺服器一直保持串連開啟,直到有資料返回。返回資料之後瀏覽器關閉串連,隨即又發起另一個伺服器請求。這一過程在頁面開啟期間一直保持連續不斷。
這種方式節省頻寬,並且遞迴請求(有順序),跟普通輪詢無序相比好很多。
testPush.html,內容如下
簡單描述:
comet是用ajax實現的伺服器推送,有兩種實現comet的方式,長輪詢和流,這裡只實現長輪詢。
長輪詢的過程:頁面發起一個伺服器請求,然後伺服器一直保持串連開啟,直到有資料返回。返回資料之後瀏覽器關閉串連,隨即又發起另一個伺服器請求。這一過程在頁面開啟期間一直保持連續不斷。
這種方式節省頻寬,並且遞迴請求(有順序),跟普通輪詢無序相比好很多。
testPush.html,內容如下
?
12345678910111213141516171819202122232425262728293031323334353637383940 |
< html > < head > < meta http-equiv = "pragma" content = "no-cache" > < meta http-equiv = "cache-control" content = "no-cache" > < meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" /> < script type = "text/javascript" src = "jquery.min.js" ></ script > < script type = "text/javascript" > $(function () { (function longPolling() { alert(Date.parse(new Date())/1000); $.ajax({ url: "testPush1111.php", data: {"timed": Date.parse(new Date())/1000}, dataType: "text", timeout: 5000,//5秒逾時,可自訂設定 error: function (XMLHttpRequest, textStatus, errorThrown) { $("#state").append("[state: " + textStatus + ", error: " + errorThrown + " ]< br />"); if (textStatus == "timeout") { // 請求逾時 longPolling(); // 遞迴調用 } else { // 其他錯誤,如網路錯誤等 longPolling(); } }, success: function (data, textStatus) { $("#state").append("[state: " + textStatus + ", data: { " + data + "} ]< br />"); if (textStatus == "success") { // 請求成功 longPolling(); } } }); })(); }); </ script > </ head > < body > < div id = "state" ></ div > </ body > </ html > |
testPush.php,內容如下
測試分析
會有幾種情況:
1.成功返回,狀態代碼200,然後再次發起長串連
2.逾時,取消(canceled)這次長串連,然後再次發起長串連
3.長串連等待中(pending),待伺服器響應
testPush.php,內容如下
?
123456789101112131415161718 |
<?php if (! $_GET [ ‘timed‘ ]) exit (); date_default_timezone_set( "PRC" ); set_time_limit(0); //無限請求逾時時間 $timed = $_GET [ ‘timed‘ ]; while (true) { sleep(3); // 休眠3秒,類比處理業務等 $i = rand(0,100); // 產生一個0-100之間的隨機數 if ( $i > 20 && $i < 56) { // 如果隨機數在20-56之間就視為有效資料,類比資料發生變化 $responseTime = time(); // 返回資料資訊,請求時間、返回資料時間、耗時 echo ( "result: " . $i . ", response time: " . $responseTime . ", request time: " . $timed . ", use time: " . ( $responseTime - $timed )); exit (); } else { // 類比沒有資料變化,將休眠 hold住串連 sleep(13); exit (); } } |
測試分析
會有幾種情況:
1.成功返回,狀態代碼200,然後再次發起長串連
2.逾時,取消(canceled)這次長串連,然後再次發起長串連
3.長串連等待中(pending),待伺服器響應
php javascript comet