How to determine if it is communicating with Indy?

I use Indy for TCP communication (D2009, Indy 10).

After evaluating the client’s request, I want to send a response to the client. Therefore, I save the TIdContext as it is (pseudocode)

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;

But what if the client terminates the connection somewhere between the request and the response, ready to be sent? How to check if context is saved? I tried

if Assigned (Context) and Assigned (Context.Connection) and Context.Connection.Connected then
  Context.Connection.IOHandler.Write ('Response');

but it doesn’t help. In some cases, the program simply freezes, and if I pause execution, I see that the current line matches the if condition.

What's going on here? How can I avoid trying to send using dead connections?

+3
source share
2 answers

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

.

+4

, / , , .

. , , - . , , . "CheckConnection" .

+2

Source: https://habr.com/ru/post/1717427/


All Articles