如何使用jQuery和";长轮询“;?
我读过这篇文章。“长轮询-一种有效的服务器推送技术”一段解释了这一点 长轮询技术结合了传统轮询的最佳情况 使用持久的远程服务器连接。长期投票 它本身是长期持有的HTTP请求的缩写如何使用jQuery和";长轮询“;?,jquery,ajax,delphi,indy,long-polling,Jquery,Ajax,Delphi,Indy,Long Polling,我读过这篇文章。“长轮询-一种有效的服务器推送技术”一段解释了这一点 长轮询技术结合了传统轮询的最佳情况 使用持久的远程服务器连接。长期投票 它本身是长期持有的HTTP请求的缩写 如何实现使用长轮询的基于Indy的HTTP服务器?这里是一个独立的示例项目,使用Indy版本10.5.9和Delphi 2009进行了测试 当应用程序运行时,导航到http://127.0.0.1:8080/。然后,服务器将提供一个HTML文档(在OnCommandGet处理程序中硬编码) 此文档包含一个div元素,该
如何实现使用长轮询的基于Indy的HTTP服务器?这里是一个独立的示例项目,使用Indy版本10.5.9和Delphi 2009进行了测试 当应用程序运行时,导航到
http://127.0.0.1:8080/
。然后,服务器将提供一个HTML文档(在OnCommandGet处理程序中硬编码)
此文档包含一个div元素,该元素将用作新数据的容器:
<body>
<div>Server time is: <div class="time"></div></div>'
</body>
与其让
TMyServer
将处理程序分配给自己继承的OnCommandGet
事件,不如让它重写虚拟TIdCustomHTTPServer.DoCommandGet()
方法。另外,在设置Response.ContentType
之后而不是之前设置Response.CharSet
。ContentType
属性设置程序可能(将来可能会)根据分配的值更改CharSet
,从而丢失手动分配。
program IndyLongPollingDemo;
{$APPTYPE CONSOLE}
uses
IdHTTPServer, IdCustomHTTPServer, IdContext, IdSocketHandle, IdGlobal,
SysUtils, Classes;
type
TMyServer = class(TIdHTTPServer)
public
procedure InitComponent; override;
procedure DoCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); override;
end;
procedure Demo;
var
Server: TMyServer;
begin
Server := TMyServer.Create(nil);
try
try
Server.Active := True;
except
on E: Exception do
begin
WriteLn(E.ClassName + ' ' + E.Message);
end;
end;
WriteLn('Hit any key to terminate.');
ReadLn;
finally
Server.Free;
end;
end;
procedure TMyServer.InitComponent;
var
Binding: TIdSocketHandle;
begin
inherited;
Bindings.Clear;
Binding := Bindings.Add;
Binding.IP := '127.0.0.1';
Binding.Port := 8080;
KeepAlive := True;
end;
procedure TMyServer.DoCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
AResponseInfo.ContentType := 'text/html';
AResponseInfo.CharSet := 'UTF-8';
if ARequestInfo.Document = '/' then
begin
AResponseInfo.ContentText :=
'<html>' + #13#10
+ '<head>' + #13#10
+ '<title>Long Poll Example</title>' + #13#10
+ ' <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"> ' +
#13#10
+ ' </script> ' + #13#10
+ ' <script type="text/javascript" charset="utf-8"> ' + #13#10
+ ' $(document).ready(function(){ ' + #13#10
+ ' (function poll(){' + #13#10
+ ' $.ajax({ url: "getdata", success: function(data){' + #13#10
+ ' $("div.time").replaceWith(data);' + #13#10
+ ' }, dataType: "html", complete: poll, timeout: 30000 });' + #13#10
+ ' })();' + #13#10
+ ' });' + #13#10
+ ' </script>' + #13#10
+ '</head>' + #13#10
+ '<body> ' + #13#10
+ ' <div>Server time is: <div class="time"></div></div>' + #13#10
+ '</body>' + #13#10
+ '</html>' + #13#10;
end
else
begin
Sleep(1000);
AResponseInfo.ContentText := '<div class="time">'+DateTimeToStr(Now)+'</div>';
end;
end;
begin
Demo;
end.