发送
try
s := 'Hello world!';
stream := TStringStream.Create(s);
IdTCPClient1.OpenWriteBuffer;
IdTCPClient1.WriteInteger(stream.Size);//注意这里:要先写入流的长度,在读取的时候如果使用 AThread.Connection.ReadStream(stream);
IdTCPClient1.WriteStream(stream, true);
finally
IdTCPClient1.CloseWriteBuffer;
stream.Free;
end;
接收
procedure TServerForm.IdTCPServer1Execute(AThread: TIdPeerThread);
var stream: Tstream;
begin
if not AThread.Terminated and AThread.Connection.Connected then
begin
stream := TStringStream.Create('');
AThread.Connection.ReadStream(stream);//这句相当于ReadStream(stream,-1,false),就是根据流的前四个字节读出流长度,然后再将流读出
stream.Position := 0;
Memo1.Lines.LoadFromStream(stream);
end;