為什么需要服務器推送事件:
因為如果需要保持前台數據的實時更新例如,IM聊天,股票信息,
1.可以在客戶端不斷地調用服務端的方法來獲得新數據,但是這樣會很消耗服務器資源,導致系統變慢!
2 html5的新特性能在服務器直接發送最新數據到前台進行顯示。
先看后台的寫法:WebForm8.aspx.cs
protected void Page_Load(object sender, EventArgs e) { Response.ContentType = "text/event-stream"; Response.Expires = -1; while (true) { Response.Write("date1235:" + DateTime.Now+"\n\n"); Thread.Sleep(2000); //向客戶端發送當前的緩沖數據 //如果你將Flush寫的循環外面,將會等循環執行完后一起顯示到前台,當然這個是死循環 Response.Flush(); } }
在看html的寫法:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm8.aspx.cs" Inherits="WebApplication1.WebForm8" %> <!DOCTYPE html><!--注意此處是HTML5的標識,寫出這樣代表目前用的html版本是5--> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div id="result"> </div> </form> </body> </html> <script type="text/javascript"> //HTML5 服務器推送事件 function ServerSendClient() { if (typeof (EventSource) !== "undefined") { var source = new EventSource("WebForm8.aspx.cs"); source.onmessage = function (event) { document.getElementById("result").innerHTML += event.data + "<br />"; }; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events..."; } } ServerSendClient(); </script>
前台截圖: