Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi Indy ReadLn with timeout

Tags:

delphi

indy

An Indy question.

I added a timeout parameter to my TIdTCPClient ReadLn call so my thread could check for terminated every so often. However, if the timeout happens, I never get any data from the ReadLn from that point on. How do I reset the TIdTCPClient so it will look for a line again?

procedure TClientListner.Execute;
var
  msg : String;

begin

  while not terminated do
  begin
    msg := fSocketCon.IOHandler.ReadLn('\n', 200);
    if not fSocketCon.IOHandler.ReadLnTimedOut then
    begin
      DoSomeThing(msg);
    end;
  end;
end;
like image 399
runfastman Avatar asked Dec 20 '22 23:12

runfastman


1 Answers

Unlike in C/C++, \ is not an escape character, so '\n' is not interpreted as a line feed in Delphi. It is a actual 2-character string, a '\' character followed by a 'n' character.

To use a real line feed as the terminator, use #10 or Indy's LF constant instead:

msg := fSocketCon.IOHandler.ReadLn(#10, 200);

msg := fSocketCon.IOHandler.ReadLn(LF, 200);

Or, use a blank string, which tells ReadLn() to use its default LF terminator:

msg := fSocketCon.IOHandler.ReadLn('', 200);

Or, don't use the ATimeout parameter at all. Use the ReadTimeout property instead, and then don't specify a terminator so the default LF terminator is used:

fSocketCon.IOHandler.ReadTimeout := 200;
...
msg := fSocketCon.IOHandler.ReadLn;
like image 121
Remy Lebeau Avatar answered Dec 24 '22 02:12

Remy Lebeau