服務(wù)熱線
153 8323 9821
在以往的和服務(wù)器端通信技術(shù)中,我們多數(shù)使用的是AJAX輪詢式訪問,也就是在Javascript中控制時間間隔,然后每隔一段時間就訪問一次服務(wù)器,然后獲得數(shù)據(jù)或通知。但是這種輪詢方式的訪問有90%是在做無用功。
要想長時間保持服務(wù)器和瀏覽器之間的連接怎么辦?長連接技術(shù),這可不是什么新技術(shù),用IFrame作為隱藏幀指向長請求頁面的方法早已被很多人運(yùn)用在互聯(lián)網(wǎng)上,但是IFrame作為隱藏幀有一個弊端,那就是瀏覽器的進(jìn)度條始終處在讀取狀態(tài)。為了使用戶獲得更好體驗,“Google的天才們”使用了一個叫“htmlfile”的對象解決了這一問題,并把它運(yùn)用了了GMail和GTalk兩個產(chǎn)品上。
如今我們公司要做的新項目上要求有實時報警功能,本來我想用AJAX輪詢做,但是覺得挺沒追求的,前段時間聽說有了Server Push,但是沒仔細(xì)研究,這次倒是個機(jī)會,一天時間,從網(wǎng)上搜集資料。資料不是很多,而且現(xiàn)在有很多開發(fā)人員還認(rèn)為長連接是天方夜譚,居然還有把HTTP協(xié)議搬出來要證明自己觀點的……
廢話不多說了,來介紹一下長連接技術(shù),通常的長鏈接就是做一個網(wǎng)頁,里面寫好一個IFrame標(biāo)簽,高寬設(shè)置為0,SRC屬性指向一個網(wǎng)頁,比如是ASPX,然后在這個文件中不做別的,只是在調(diào)用Context.Response.Write方法,輸出什么?比如客戶端有一個更改時間的方法Change(time),那輸出就是("<script>window.parent.Change("+DateTime.Now.ToString()+")</script>"),也就是不斷的輸出客戶端的函數(shù)調(diào)用,并且做成死循環(huán),這樣瀏覽器和服務(wù)器端就形成了一條源源不斷的數(shù)據(jù)傳輸鏈接。
那htmlfile是什么呢?這是一個類似Javascript中Window對象的一個ActiveXObject,它內(nèi)部也是DOM結(jié)構(gòu),將作為隱藏幀的IFrame寫入這個對象中,就可以解決進(jìn)度條的問題。說的可能比較晦澀,來看實例代碼吧:
Default.aspx.cs
C#代碼
1.public partial class _Default : System.Web.UI.Page
2.{
3.protected void Page_Load(object sender, EventArgs e)
4.{
5.}
6.protected override void Render(HtmlTextWriter output)
7.{
8.string str;
9.while (true)
10.{//死循環(huán)保持長鏈接
11.str = "<script >window.parent.Change("" + DateTime.Now.ToLongTimeString() + "")</script>";
12.this.Context.Response.Write(str);
13.this.Context.Response.Flush();//輸腳本調(diào)用出
14.System.Threading.Thread.Sleep(1000);
15.}
16.}
17.}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void Render(HtmlTextWriter output)
{
string str;
while (true)
{//死循環(huán)保持長鏈接
str = "<script >window.parent.Change("" + DateTime.Now.ToLongTimeString() + "")</script>";
this.Context.Response.Write(str);
this.Context.Response.Flush();//輸腳本調(diào)用出
System.Threading.Thread.Sleep(1000);
}
}
}
WebForm1.aspx
Html代碼
1.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>
2.<html xmlns="http://www.w3.org/1999/xhtml">
3.<head runat="server">
4.<title>Asp.net Server Push</title>
5.<script type="text/javascript">
6.function Change(str){
7.window.document.getElementById("div1").innerText=str;
8.}
9.function onload(){
10.var ifrpush = new ActiveXObject("htmlfile"); // 創(chuàng)建對象
11.ifrpush.open(); //打開
12.var ifrDiv = ifrpush.createElement("div"); //添加一個DIV
13.ifrpush.appendChild(ifrDiv); //添加到 htmlfile
14.ifrpush.parentWindow.Change=Change; //注冊 javascript 方法 搞不明白為什么還要注冊
15.ifrDiv.innerHTML = "<iframe src="Default.aspx"></iframe>"; //在div里添加 iframe
16.ifrpush.close(); //關(guān)閉
17.}
18.onload();
19.</script>
20.</head>
21.<body>
22.<div style=" float:left">現(xiàn)在時間是:</div>
23.<div id="div1"></div>
24.</body>
25.</html>