Search code examples
delphisocketsindydisconnect

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.


Solution

  • 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;