Delphi Indy10:IdTCPClient如何获取Server的响应,且响应长度未知

发布于 2024-09-16 19:49:38 字数 380 浏览 3 评论 0原文

主机:127.00.0.1; 端口:5001; 读取超时:3000;

//Following codes to get the response
procedure TForm1.Button2Click(Sender: TObject);
var
  s:string;
begin
  try
    while True do
    begin
      s := s+IdTCPClient1.IOHandler.ReadChar();
    end;
  finally
     showmessage(s);
....other operations...
  end;
//....

当超时时,其他操作的一部分将不会被执行。有什么想法可以继续代码吗?谢谢。

host:127.00.0.1;
port:5001;
ReadTimeout:3000;

//Following codes to get the response
procedure TForm1.Button2Click(Sender: TObject);
var
  s:string;
begin
  try
    while True do
    begin
      s := s+IdTCPClient1.IOHandler.ReadChar();
    end;
  finally
     showmessage(s);
....other operations...
  end;
//....

When timerout the part of other operations will not be excuted.Any ideas to contionu the code?Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

强辩 2024-09-23 19:49:38

如果 ReadTimeout 超时,ReadChar() 将引发 EIdReadTimeout 异常。您需要使用 try/ except 块来捕获它,例如:

procedure TForm1.Button2Click(Sender: TObject);
var
  s: string;
begin
  try
    repeat
      try
        s := s + IdTCPClient1.IOHandler.ReadChar();
      except
        on E: EIdReadTimeout do Break;
      end;
    until False;
  finally
    ShowMessage(s);
    ...
  end;
//.... 

更好的选择是根本不在循环中调用 ReadChar() 。请改用 IOHandler 的 CheckForDataOnSource() 和 InputBufferAsString() 方法,例如:

procedure TForm1.Button2Click(Sender: TObject);
var
  s: string;
begin
  try
    while IdTCPClient1.IOHandler.CheckForDataOnSource(IdTimeoutDefault) do begin end;
  finally
    s := IdTCPClient1.IOHandler.InputBufferAsString;
    ShowMessage(s);
    ...
  end; 
//.... 

ReadChar() will raise an EIdReadTimeout exception if the ReadTimeout elapses. You need to use a try/except block to catch that, eg:

procedure TForm1.Button2Click(Sender: TObject);
var
  s: string;
begin
  try
    repeat
      try
        s := s + IdTCPClient1.IOHandler.ReadChar();
      except
        on E: EIdReadTimeout do Break;
      end;
    until False;
  finally
    ShowMessage(s);
    ...
  end;
//.... 

A better option is to not call ReadChar() in a loop at all. Use the IOHandler's CheckForDataOnSource() and InputBufferAsString() methods instead, eg:

procedure TForm1.Button2Click(Sender: TObject);
var
  s: string;
begin
  try
    while IdTCPClient1.IOHandler.CheckForDataOnSource(IdTimeoutDefault) do begin end;
  finally
    s := IdTCPClient1.IOHandler.InputBufferAsString;
    ShowMessage(s);
    ...
  end; 
//.... 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文