Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

delphi - TCP Keep Alive on idHttpServer (server) and wininet (client)

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 - 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 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.

  • Is this possible to be used with idHttpServer (for the server) and wininet functions (for the client)?
  • Does that really works as expected? I mean, the server gets notfied when the client dies all the times?
  • Does anyone have a sample of setting this on wininet? (I guess this must be set on the client side, right?)
  • Is there a better way of notify a server that the client is dead (using indy and wininet, of course)

EDIT

I am using Delphi 2010 and last Indy10 source code from their svn.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

For example:

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;

Note that the ATimeMS and AInterval parameters are only supported on Win2K and later.

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);

For example:

procedure TForm1.IdHTTPServer1Connect(AContext: TIdContext);
begin
  AContext.Binding.SetSockOpt(Id_SOL_SOCKET, Id_SO_KEEPALIVE, 1);
end;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...