我认为最好的是使用Comet http://en.wikipedia.org/wiki/Comet_%28programming%29.
在Comet风格的应用程序中,服务器本质上可以将数据推送到客户端(而不是客户端一次又一次地向服务器请求数据)。客户端只需要连接到服务器once。然后服务器会不断将数据推送回客户端。
来自维基百科:
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
of 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(); };
参考 http://www.aaronlerch.com/blog/2007/07/08/creating-comet-applications-with-aspnet/