如何使用Delphi中的Indy Client从服务器读取所有字节?

5 delphi indy indy10 delphi-xe2

我正在使用Indy客户端来读取服务器发送给我的消息(客户端).它一次性向我发送512字节的数据.这512字节的数据由两种数据类型(Word和String)组成.例如,它发送2个字节的字,然后再发送2个字节的字,然后发送50个字节的字符串,依此类推.我正在尝试使用代码来解决这个问题:

var BufferArray : Array[0..512] of Byte;

 if IdTCPClient1.IOHandler.InputBufferIsEmpty then
 begin
      if IdTCPClient1.IOHandler.CheckForDataOnSource(1000) then
      begin
          Edit1.Text := idtcpclient1.IOHandler.ReadBytes(BufferArray ,512, true);
      end;
 end;
Run Code Online (Sandbox Code Playgroud)

我在线上遇到错误Edit1.Text:= idtcpclient1.IOHandler.ReadBytes(BufferArray,512,true); 错误:实际和正式var参数的类型必须相同.

这是我使用的正确方法.我想在Edit1.Text上存储整个512字节,然后我将对该数据执行任何操作.请帮我从服务器获取所有512个字节.

更新:交替方法

我正在使用这种方法来读取单词和字符串值

WordArray : array[0..5] of word;

 if IdTCPClient1.IOHandler.InputBufferIsEmpty then
 begin
      if IdTCPClient1.IOHandler.CheckForDataOnSource(1000) then
      begin
        i := 0;
        while i < 6 do //Read all the words
        begin
            //Fill WORD data in array
            WordArray[i] :=  (IdTCPClient1.Socket.ReadWord(True));
        end;
      end;
end;
Run Code Online (Sandbox Code Playgroud)

类似于字符串的方法

WordArray [i]:=(IdTCPClient1.Socket.ReadString(50));

这很好,但我必须在循环中读取所有数据时保持连接打开.如果在连接之间,我会丢失所有内容,并且必须再次从服务器请求整个包.

TLa*_*ama 1

除非你准确地描述你所拥有的文档中所写的内容,否则很难回答你。到目前为止,我们知道您的 512B 数据包由 6 个字和 10x50B 字符串组成。因此,请将此作为起点,直到您告诉我们更多信息:

procedure TForm1.Button1Click(Sender: TObject);
var
  I: Integer;
  Buffer: TBytes;
  WordArray: array[0..5] of Word;
  StringArray: array[0..9] of AnsiString;
begin
  if IdTCPClient1.IOHandler.InputBufferIsEmpty then
  begin
    if IdTCPClient1.IOHandler.CheckForDataOnSource(1000) then
      IdTCPClient1.IOHandler.ReadBytes(Buffer, 512, False);

    for I := 0 to High(WordArray) do
    begin
      WordRec(WordArray[I]).Hi := Buffer[I * 2];
      WordRec(WordArray[I]).Lo := Buffer[I * 2 + 1];
    end;
    for I := 0 to High(StringArray) do
      SetString(StringArray[I], PAnsiChar(@Buffer[I * 50 + 12]), 50);

    // here you have the arrays prepared to be processed
  end;
end;
Run Code Online (Sandbox Code Playgroud)