如何确定Indy的连接是否仍然存在?

jpf*_*ius 4 delphi tcp indy delphi-2009

我使用Indy进行TCP通信(D2009,Indy 10).

在评估客户端请求后,我想将答案发送给客户端.因此我存储TIdContext,就像这样(伪代码)

procedure ConnectionManager.OnIncomingRequest (Context : TIdContext);
begin
  Task := TTask.Create;
  Task.Context := Context;
  ThreadPool.AddTask (Task);
end;

procedure ThreadPool.Execute (Task : TTask);
begin
  // Perform some computation
  Context.Connection.IOHandler.Write ('Response');
end;
Run Code Online (Sandbox Code Playgroud)

但是,如果客户端在请求和准备发送的答案之间的某处终止连接,该怎么办?如何检查上下文是否仍然有效?我试过了

if Assigned (Context) and Assigned (Context.Connection) and Context.Connection.Connected then
  Context.Connection.IOHandler.Write ('Response');
Run Code Online (Sandbox Code Playgroud)

但它没有帮助.在某些情况下,程序只是挂起,如果我暂停执行,我可以看到当前行是if条件的行.

这里发生了什么?如何避免尝试使用死连接发送?

jpf*_*ius 5

好的,我找到了解决方案.我没有存储TIdContext,而是使用TIdTcpServer提供的上下文列表:

procedure ThreadPool.Execute (Task : TTask);
var
  ContextList : TList;
  Context : TIdContext;
  FoundContext : Boolean;
begin
  // Perform some computation

  FoundContext := False;
  ContextList := FIdTCPServer.Contexts.LockList;
  try
    for I := 0 to ContextList.Count-1 do
      begin
      Context := TObject (ContextList [I]) as TIdContext;
      if (Context.Connection.Socket.Binding.PeerIP = Task.ClientInfo.IP) and
         (Context.Connection.Socket.Binding.PeerPort = Task.ClientInfo.Port) then
        begin
        FoundContext := True;
        Break;
        end;
      end;
  finally
    FIdTCPServer.Contexts.UnlockList;
  end;

  if not FoundContext then
    Exit;

  // Context is a valid connection, send the answer

end;          
Run Code Online (Sandbox Code Playgroud)

这对我行得通.