Raf*_*cci 5 delphi tcp wininet indy keep-alive
我有一个使用idHttpServer开发的Web服务器应用程序。当客户端连接时,请执行我的Web服务器,并且由于某种未知原因而断开连接(不是正常断开连接),则不会通知我的Web服务器。我知道这是正常的行为,但是我需要知道客户死亡的时间。
有几种方法可以做到这一点。我知道2种好方法:
1-实施心跳机制。客户端套接字通知服务器它仍在运行(需要一些工作和一些代码才能使其工作)
2- TCP保持活动。这是我最喜欢的方式,因为它不需要太多的代码和工作。但是我对此有一些疑问。
编辑
我正在使用Delphi 2010和他们svn的最后一个Indy10源代码。
如果您使用的是最新的 Indy 10 版本,那么您可以使用以下TIdSocketHandle.SetKeepAliveValues()方法:
procedure SetKeepAliveValues(const AEnabled: Boolean; const ATimeMS, AInterval: Integer);
Run Code Online (Sandbox Code Playgroud)
例如:
procedure TForm1.IdHTTPServer1Connect(AContext: TIdContext);
begin
// send a keep-alive every 1 second after
// 5 seconds of inactivity has been detected
AContext.Binding.SetKeepAliveValues(True, 5000, 1000);
end;
Run Code Online (Sandbox Code Playgroud)
请注意,ATimeMS和AInterval参数仅在 Win2K 及更高版本上受支持。
否则,直接使用TIdSocketHandle.SetSockOpt()方法手动启用 TCP/IPSO_KEEPALIVE选项:
procedure TIdSocketHandle.SetSockOpt(ALevel: TIdSocketOptionLevel; AOptName: TIdSocketOption; AOptVal: Integer);
Run Code Online (Sandbox Code Playgroud)
例如:
procedure TForm1.IdHTTPServer1Connect(AContext: TIdContext);
begin
AContext.Binding.SetSockOpt(Id_SOL_SOCKET, Id_SO_KEEPALIVE, 1);
end;
Run Code Online (Sandbox Code Playgroud)