TCP Keep Alive on idHttpServer(服务器)和 wininet(客户端) [英] TCP Keep Alive on idHttpServer (server) and wininet (client)
问题描述
我有一个使用 idHttpServer 开发的网络服务器应用程序.当客户端连接我的网络服务器时,由于某种未知原因,断开连接(不是正常断开连接)我的网络服务器没有得到通知.我知道这是正常行为,但我需要知道客户端何时死亡.
I have a webserver application developed using idHttpServer. When a client connects do my webserver and, for some unknown reason, got disconnect (not a gracefully disconnect) my webserver does not get notified. I know this is the normal behavior but I need to know when the client dies.
有几种方法可以做到这一点.我知道两个好方法:
There are a few ways of doing this. I know 2 good ways:
1 - 实现心跳机制.客户端套接字通知服务器它仍然活着(需要一些工作和一些代码才能使其工作)
1 - Implement a heart beat mechanism. The client socket notifies the server that it is still alive (need some work and some code to make it works)
2 - TCP 保持活动.这是我最喜欢的方式,因为它不需要太多的代码和工作.但我对此有一些疑问.
2 - TCP Keep Alive. This is the way I like most because it requires not too much code and work. But I got a few questions regarding this.
- 这是否可以与idHttpServer(用于服务器)和wininet 函数(用于客户端)?
- 这真的按预期工作吗?我的意思是,当客户端一直死掉时,服务器会收到通知?
- 有没有人有在 wininet 上设置这个的示例?(我想这必须在客户端设置,对吗?)
- 是否有更好的方法通知服务器客户端已死(当然使用 indy 和 wininet)
编辑
我使用的是 Delphi 2010 和来自他们 svn 的最新 Indy10 源代码.
I am using Delphi 2010 and last Indy10 source code from their svn.
推荐答案
如果您使用的是最新的 Indy 10 版本,那么您可以使用 TIdSocketHandle.SetKeepAliveValues()
方法:
If you are using an up-to-date Indy 10 release, then you can use the TIdSocketHandle.SetKeepAliveValues()
method:
procedure SetKeepAliveValues(const AEnabled: Boolean; const ATimeMS, AInterval: Integer);
例如:
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;
请注意,ATimeMS
和 AInterval
参数仅在 Win2K 及更高版本上受支持.
Note that the ATimeMS
and AInterval
parameters are only supported on Win2K and later.
否则,直接使用TIdSocketHandle.SetSockOpt()
方法手动开启TCP/IPSO_KEEPALIVE
选项:
Otherwise, use the TIdSocketHandle.SetSockOpt()
method directly to enable the TCP/IP SO_KEEPALIVE
option manually:
procedure TIdSocketHandle.SetSockOpt(ALevel: TIdSocketOptionLevel; AOptName: TIdSocketOption; AOptVal: Integer);
例如:
procedure TForm1.IdHTTPServer1Connect(AContext: TIdContext);
begin
AContext.Binding.SetSockOpt(Id_SOL_SOCKET, Id_SO_KEEPALIVE, 1);
end;
这篇关于TCP Keep Alive on idHttpServer(服务器)和 wininet(客户端)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!