Indy throws off multiple Exceptions when closing a socket. How to do a clean automatic reconnect?

I have a Delphi 6 application that uses the Indy 9 components to maintain a persistent IdTCPConnection with an external device. Some times I want to break the connection and then reconnect to the device. I have found when I do that Indy throws off as many as 3 separate Exceptions. This has made developing a clean reconnection strategy somewhat messy since the Indy component is on a background thread and I don't want to break the thread Execute() loop.

What is a good or clean way to absorb the 3 Exceptions before I attempt to reconnect? The 3 Exceptions I have seen are, in order of appearance, EIdClosedSocket, EIdConnClosedGracefully, EIdSocketError (with LastError = WSAECONNABORTED). I want to wait until all Exceptions related to the closing of the socket have propagated before attempting to reconnect, but I'm not sure how to structure my code loop to do that.

Answers


Only one exception will reach your thread's code at a time. Simply wrap the code inside your thread loop with a try/except block and then reconnect on the next loop iteration.

while not Terminated do
begin
  if not Client.Connected then
  try
    Client.Connect;
  except
    Sleep(2500);
    Continue;
  end;
  try
    // communicate with device as needed...
  except
    on E: EIdException do
    begin
      // Indy socket error, reconnect
      Client.Disconnect;
      Client.InputBuffer.Clear;
    end;
    on E: Exception do
    begin
      // something else happened in your code...
    end;
  end;
end;

Need Your Help

c# - Using objects deleted from context in Entity Framework

c# entity-framework sql-delete

Using code-first, I had doubts over what would happen if I obtained an object by querying the database, but kept using it after having it deleted or removed from the database.

Comparison between CAB vs Prism

c# wpf winforms prism cab

I have Winform that needs rewrite. I know we have Prism in WPF. For those who have been through both, what are the important differences between these two frameworks? I am a CAB programmer, so I al...