6
在Delphi XE2我有具有以下結構的記錄類型:發送並用TidTCPClient和TidTCPServer接收流在Delphi XE2
TMachinInfoRec = record
IPStr: string[15];
Username: string[50];
Computername: string[100];
SentTime: TDateTime;
HasCommand: integer;
ClientCommands: array[0..9] of TMachineCommand;
end;
我定義在客戶端側上其和內存流變量的變量和發送流與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 ..,....... @ ......... ..........................,....
我該如何解決這個問題?
當移動不同進程之間或在I/O,聲明記錄與'packed'指令記錄結構。否則可能會出現對齊問題。我並不是說這裏就是這種情況,但稍後可能會發生潛在的錯誤。 – 2012-02-25 10:45:20
不要忘記調用'ReadStream()'之後,調用'Read()'之前,將流的'Position'重置爲0。或者,使用'TIdMemoryBufferStream'而不是'TMemoryStream'來讓Indy直接讀/寫你的記錄變量。 – 2012-02-25 16:42:21