Delphi: Setting connection timeout for TIdHttpServer

妖精的绣舞 提交于 2019-12-10 11:07:18

问题


Using TIdHTTPServer (Indy 10.6), i want set a connection timeout for close slow or inactive client (client are common browser) and close all zombie connection after 60 seconds of inactivity. I have found Socket.ReadTimeout in TIdContext.Connection. Is this the right way? TIdHTTPServer already perform this (it seem have infinite timeout)?

WebServer := TIdHTTPServer.Create(nil);
WebServer.SessionState := false;
WebServer.KeepAlive    := false;
WebServer.OnCommandGet := CustomOnCommandGet;

procedure CustomOnCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo;
begin
    AContext.Connection.Socket.ReadTimeout := 60000;
    AResponseInfo.ContentStream := TFileStream.Create('C:/file.zip', fmOpenRead or fmShareCompat);
end;

回答1:


You are on the right track, the ReadTimeout property can be used to disconnect slow/dead clients that do not send requests in a timely manner. However, you are setting ReadTimeout in the wrong place.

By the time an OnCommand... event is triggered, TIdHTTPServer has already read the client's request in full, so your new setting will not take effect until the next request on the same connection, if any. So, you should set the ReadTimeout value in the OnConnect event instead:

WebServer.OnConnect := CustomOnConnect;

procedure CustomOnConnect(AContext: TIdContext);
begin
  AContext.Connection.Socket.ReadTimeout := 60000;
end;

Remember that HTTP is stateless. Multiple HTTP requests can be sent on the same connection only if HTTP keep-alives are used, which is optional. Without keep-alives, the server closes the connection after sending a response. A client would have to reconnect to send a new request.

You are setting the server's KeepAlive property to false, so there will not be any keep-alives honored, every request will be followed by a disconnect. So, you need to set ReadTimeout in the OnConnect event to apply it to the sole request sent on each connection. But, if you enable KeepAlive, and a client requests a keep-alive, then the ReadTimeout will apply to every request that client sends on the same connection, especially the first request.



来源:https://stackoverflow.com/questions/35101959/delphi-setting-connection-timeout-for-tidhttpserver

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!