0

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.

Robert Oschler
  • 14,153
  • 18
  • 94
  • 227

1 Answers1

2

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;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • but then the "extra" Exceptions will cause the Except block to fire again when instead I want the newly reconnected connection to stay viable. Is that correct? Won't that be a problem? BTW, if you get the chance, I'd like your opinion on another post I have open on Stack Overflow regarding refreshing the codec list presented by AviSaveOptions(): http://stackoverflow.com/questions/11013713/how-do-i-refresh-the-video-codecs-shown-in-the-list-presented-by-avisaveoptions – Robert Oschler Jun 14 '12 at 16:25
  • 2
    No, what you describe is not correct. As I said, only one exception will reache your code. It may be `EIdClosedSocket` OR `EIdConnClosedGracefully` OR `EIdSocketError`, but never all three at once. And `Disconnect()` itself should not be raising any exception at all, but if it is, try using `DisconnectSocket()` instead. – Remy Lebeau Jun 14 '12 at 18:29
  • Ok, thanks. For some reason I got the impression I was getting hit by more than one Exception, but it may have been due to where I was setting breakpoints and seeing Exceptions from more than one instance of the component and misinterpreting them as being all for the same instance. – Robert Oschler Jun 14 '12 at 18:58