I am writing an application, which uses TIdTCPClient
to communicated with another application via a socket.
I want the application to try to connect to a certain server until the connection is established (i. e. until the server has gone online).
In order to do this, I wrote following code:
procedure SendingThread.Execute();
var
I : integer;
Test : string;
IsConnected : Boolean;
begin
TcpClient := TIdTCPClient.Create;
TcpClient.Host := '127.0.0.1';
TcpClient.Port := 9999;
TcpClient.ConnectTimeout := 60000;
IsConnected := false;
while not IsConnected do
begin
try
TcpClient.Connect;
IsConnected := True;
except
on E:EIdSocketError do
IsConnected := false;
end;
end;
...
end;
When I run this code with server being offline, I get EIdSocketError
with error code 10061
. The exception is thrown after TcpClient.Connect;
.
How can I modify the code so that this exception in caught in the except
cause?
TIdTCPClient.Connect
is synchronous, so the code you've posted is fine except that you should modify your loop to check alsoTerminated
flag of a thread likewhile not Terminated and not IsConnected do
and except that you can get into infinite connection attempt loop. But you can't get to the lineIsConnected := True;
after theTcpClient.Connect;
is called and the connection fails. – Udderwhile (not IsConnected) and (not Terminated) do
doesn't fix the error (tried it). – PantieIsConnected := True;
(with the current code) if you'll attempt to connect to a not existing server. – Udder