使用Delphi XE2中的TidTCPClient和TidTCPServer发送和接收流

时间:2012-02-25 10:14:55

标签: delphi delphi-xe2 indy

在Delphi XE2中,我有一个具有以下结构的记录类型:

  TMachinInfoRec = record
    IPStr: string[15];
    Username: string[50];
    Computername: string[100];
    SentTime: TDateTime;
    HasCommand: integer; 
    ClientCommands: array[0..9] of TMachineCommand;
  end;

我在客户端和TMemoryStream变量上定义一个变量,并使用TidTCPClient组件发送流:

var
  MIRec: TMachinInfoRec;
  msRecInfo: TMemoryStream;

begin
  MIRec.IPStr = '192.168.100.101';
  MIRec.Username := 'user-a';
  MIRec.Computername := 'Computer-a';
  MIRec.SentTime := Now();

  idTCPClient.Host := '192.168.100.138';
  idTCPClient.Port := 6000;

  idTCPClient.Connect;

  msRecInfo := TMemoryStream.Create;
  msRecInfo.Write(msRecInfo, SizeOf(Client));

  msRecInfo.Position := 0;
  idTCPClient.IOHandler.Write(msRecInfo);
end;

并使用TidTCPServer在服务器端获取信息:

procedure TFrmMainServer.TCPServerExecute(AContext: TIdContext);
var
  MIRec: TMachinInfoRec;
  msRecInfo: TMemoryStream;
begin
  msRecInfo:= TMemoryStream.Create;

  AContext.Connection.IOHandler.ReadStream(msRecInfo, SizeOf(MIRec));

  msRecInfo.Read(msRecInfo, sizeOf(MIRec));

  ShowMessage(MIRec.IPStr);
  ShowMessage(MIRec.Computername)
end;

但是以这种格式显示的字符串:

  

MZ?......... YY ..,....... @ ........................ ...........,....

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:7)

不应该

     msRecInfo.Write(msRecInfo, SizeOf(Client));

     msRecInfo.Write(miRec, SizeOf(miRec));

阅读相同:

     msRecInfo.Read(miRec, sizeOf(MIRec));

请注意,此代码还有其他几个不确定因素:

  • 什么是“客户”? OTOH,经过上述更正后,就会被取消。
  • 我们无法从此代码确认TMachineCommand不是指针类型