Asynchronous read using TIdTCPClient

Viewed 3223

I´m new to Delphi and I´m trying to do some networks operations. In this case I want to connect to a (let´s call it) a notification server that will send strings whenever some event occurs.

My first approach is this one: I run the TIdTCPClient on its own thread and set a ReadTimeout so I´m not always blocked. This way I can check the Terminated status of the thread.

ConnectionToServer.ReadTimeout := MyTimeOut;
while( Continue ) do
begin
    //
    try
        Command := ConnectionToServer.ReadLn( );
    except
    on E: EIdReadTimeout do
        begin
                //AnotarMensaje(odDepurar, 'Timeout ' + E.Message );
        end;
    on E: EIdConnClosedGracefully do
        begin
                AnotarMensaje(odDepurar, 'Conexión cerrada ' + E.Message );
                Continue := false;
        end;
    on E: Exception do
        begin
                AnotarMensaje(odDepurar, 'Error en lectura ' + E.Message );
                Continue := false;
        end;
    end;
    // treat the command
    ExecuteRemoteCommand( Command );    
    if( self.Terminated ) then
    begin
        Continue := false;
    end;
end;    // while continue

Reading the ReadLn code I´ve seen that it´s doing some active wait in a repeat until loop that checks some buffer size all the time.

Is there a way to do this asynchronously in the way that TIdTCPServer works with the OnExecute, etc methods? Or, at least, some way to avoid that active wait.

2 Answers
Related