我读过使用JavaScript和jQuery的简单长轮询示例这篇文章。“长轮询-一种高效的服务器推送技术”一段解释了
长轮询技术结合了最好的传统轮询和持久的远程服务器连接.长期轮询本身是长期持有的HTTP请求的缩写。
如何实现使用长轮询的基于Indy的HTTP服务器?
发布于 2013-01-12 10:38:10
下面是一个独立的示例项目,使用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>
然后,JavaScript代码向循环中的资源/getdata
发送请求(函数poll()
)。
服务器使用一个HTML片段进行响应,该片段包含一个新的<div>
元素,该元素具有当前服务器时间。然后,JavaScript代码将旧的<div>
元素替换为新的。
若要模拟服务器工作,该方法在返回数据之前等待一秒钟。
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.
https://stackoverflow.com/questions/14292475
复制相似问题