我认为最好是使用Comet。
在Comet样式的应用程序中,服务器实际上可以将数据推送到客户端(而不是客户端一次又一次从服务器请求数据)。客户端只需连接 一次 服务器 即可
。然后服务器将继续将数据推回客户端。
从维基百科:
Comet是一种编程技术,可使Web服务器将数据发送到客户端,而无需客户端请求。它允许创建事件驱动的Web应用程序,该应用程序托管在浏览器中。
现在让我们看看Comet的工作原理。请参阅以下服务器端代码。这里使用了一个
while循环,您可以设置自己的条件。在while循环中,页面写入日期时间并刷新,然后睡眠1/2秒。
ASP.NET页面的代码隐藏:Service.aspx.cs
public static string Delimiter = "|";protected void Page_Load(object sender, EventArgs e){ Response.Buffer = false; while (true) { Response.Write(Delimiter + DateTime.Now.ToString("HH:mm:ss.FFF")); Response.Flush(); // Suspend the thread for 1/2 a second System.Threading.Thread.Sleep(500); } // Yes I know we'll never get here, // it's just hard not to include it! Response.End();}客户端代码-纯Javascript
只有做出一次请求,然后守在检查数据
readyState === 3的
XMLHttpRequest。
function getData(){ loadXMLDoc("Service.aspx");}var req = false;function createRequest() { req = new XMLHttpRequest(); // http://msdn.microsoft.com/en-us/library/ms535874%28v=vs.85%29.aspx}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); // At some (artibrary) length recycle the connection if (req.responseText.length > 3000) { lastDelimiterPosition = -1; getData(); } } catch (e) { alert(e.message); } }}var lastDelimiterPosition = -1;function ProcessInput(input) { // Make a copy of the input var text = input; // Search for the last instance of the delimiter var nextDelimiter = text.indexOf('|', lastDelimiterPosition + 1); if (nextDelimiter != -1) { // Pull out the latest message var timeStamp = text.substring(nextDelimiter + 1); if (timeStamp.length > 0) { lastDelimiterPosition = nextDelimiter; document.getElementById('outputZone').innerHTML = timeStamp; } }}window.onload = function () { getData(); };参考



