服務熱線
153 8323 9821
在以往的和服務器端通信技術中,我們多數使用的是AJAX輪詢式訪問,也就是在Javascript中控制時間間隔,然后每隔一段時間就訪問一次服務器,然后獲得數據或通知。但是這種輪詢方式的訪問有90%是在做無用功。
要想長時間保持服務器和瀏覽器之間的連接怎么辦?長連接技術,這可不是什么新技術,用IFrame作為隱藏幀指向長請求頁面的方法早已被很多人運用在互聯網上,但是IFrame作為隱藏幀有一個弊端,那就是瀏覽器的進度條始終處在讀取狀態。為了使用戶獲得更好體驗,“Google的天才們”使用了一個叫“htmlfile”的對象解決了這一問題,并把它運用了了GMail和GTalk兩個產品上。
如今我們公司要做的新項目上要求有實時報警功能,本來我想用AJAX輪詢做,但是覺得挺沒追求的,前段時間聽說有了Server Push,但是沒仔細研究,這次倒是個機會,一天時間,從網上搜集資料。資料不是很多,而且現在有很多開發人員還認為長連接是天方夜譚,居然還有把HTTP協議搬出來要證明自己觀點的……
廢話不多說了,來介紹一下長連接技術,通常的長鏈接就是做一個網頁,里面寫好一個IFrame標簽,高寬設置為0,SRC屬性指向一個網頁,比如是ASPX,然后在這個文件中不做別的,只是在調用Context.Response.Write方法,輸出什么?比如客戶端有一個更改時間的方法Change(time),那輸出就是("<script>window.parent.Change("+DateTime.Now.ToString()+")</script>"),也就是不斷的輸出客戶端的函數調用,并且做成死循環,這樣瀏覽器和服務器端就形成了一條源源不斷的數據傳輸鏈接。
那htmlfile是什么呢?這是一個類似Javascript中Window對象的一個ActiveXObject,它內部也是DOM結構,將作為隱藏幀的IFrame寫入這個對象中,就可以解決進度條的問題。說的可能比較晦澀,來看實例代碼吧:
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.{//死循環保持長鏈接
11.str = "<script >window.parent.Change("" + DateTime.Now.ToLongTimeString() + "")</script>";
12.this.Context.Response.Write(str);
13.this.Context.Response.Flush();//輸腳本調用出
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)
{//死循環保持長鏈接
str = "<script >window.parent.Change("" + DateTime.Now.ToLongTimeString() + "")</script>";
this.Context.Response.Write(str);
this.Context.Response.Flush();//輸腳本調用出
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"); // 創建對象
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(); //關閉
17.}
18.onload();
19.</script>
20.</head>
21.<body>
22.<div style=" float:left">現在時間是:</div>
23.<div id="div1"></div>
24.</body>
25.</html>
上一篇:如何優化你的網站.
下一篇:SQL日期時間轉為字符串