Delphi:设置TIdHttpServer的连接超时
使用TIdHTTPServer(Indy 10.6),我要为关闭缓慢或不活动的客户端(客户端是常见的浏览器)设置连接超时,并在60秒不活动后关闭所有僵尸连接.我在TIdContext.Connection中找到Socket.ReadTimeout.这是正确的方法吗? TIdHTTPServer已经执行了此操作(似乎有无限超时)?
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;
您在正确的轨道上,ReadTimeout
属性可用于断开不及时发送请求的慢速/死客户端.但是,您将ReadTimeout
设置在错误的位置.
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.
在触发OnCommand...
事件时,TIdHTTPServer
已经完全读取了客户端的请求,因此,直到同一连接上的 next 请求,您的新设置才会生效,如果有的话.因此,您应该改为在OnConnect
事件中设置ReadTimeout
值:
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;
请记住,HTTP是无状态的.仅当使用 HTTP保持活动时,才能在同一连接上发送多个HTTP请求.这是可选的.如果没有保持活动状态,则服务器在发送响应后关闭连接.客户端必须重新连接才能发送新请求.
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.
您正在将服务器的KeepAlive
属性设置为false,因此将不执行任何保持活动状态,每个请求后都将断开连接.因此,您需要在OnConnect
事件中设置ReadTimeout
,以将其应用于在每个连接上发送的唯一请求.但是,如果启用KeepAlive
,并且客户端请求保持活动状态,则ReadTimeout
将应用于客户端在同一连接上发送的每个请求,尤其是第一个请求.
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.