Indy TCP - Read data in a loop

后端 未结 1 1697
醉酒成梦
醉酒成梦 2021-02-06 17:16

A TCP server is sending data frames continuosly every 8ms. I want to program a client able to receive these data frames. Is there any procedure in Indy 9 to know if there is dat

1条回答
  •  情书的邮戳
    2021-02-06 17:38

    TIdTCPClient is not an asynchronous component. It does not tell you when data arrives. You need to use a Timer or a Thread to periodically poll the socket for new data (TIdUDPServer uses an internal thread to trigger its OnUDPRead event), eg:

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      IdTCPClient1.Connect;
      Timer1.Enabled := True;
    end;
    
    procedure TForm1.Button2Click(Sender: TObject);
    begin
      Timer1.Enabled := False;
      IdTCPClient1.Disconnect;
    end;
    
    procedure TForm1.Timer1Timer(Sender: TObject);
    var
      s1: string;
    begin
      s1 := IdTCPClient1.CurrentReadBuffer;
      ...
    end;
    

    With that said, CurrentReadBuffer() is generally not the best choice to use. Typically you would do something more like this instead:

    procedure TForm1.Timer1Timer(Sender: TObject);
    begin
      Timer1.Enabled := False;
    
      IdTCPClient1.ReadFromStack(True, 0, False);
    
      while IdTCPClient1.InputBuffer.Size > 0 do
      begin
        // read one complete frame and process as needed ...
      end;
    
      Timer1.Enabled := True;
    end;
    

    Update: given new information about the frame structure and your switch to a thread, you should be doing this instead:

    procedure TThreadRead.Execute;
    var
      buffer: array of Byte;
      numbytes: Integer;
    begin
      SetLength(buffer, 0);
      IdTCPClient1.Connect;
      try
        while not Terminated do
        begin
          numbytes := StrToInt('$' + IdTCPClient1.ReadString(8)) - 8;
          if numbytes <> Length(buffer) then
            SetLength(buffer, numbytes);
          if numbytes > 0 then
            IdTCPClient1.ReadBuffer(buffer[0], numbytes);
          // process buffer up to numbytes as needed...
        end;
      finally
        IdTCPClient1.Disconnect;
      end;
    end;
    

    0 讨论(0)
提交回复
热议问题