客戶端發送流到服務器端有幾種方式,這裡討論兩種:
1.客戶端連接到服務器後,發送一個流,服務器接收一個流。
{*------------------------------------------------------------------------------
客戶端發送流,假定已經建立連接
------------------------------------------------------------------------------*}
procedure TClientForm.Button3Click(Sender: TObject);
var s: string; stream: TStream;
begin
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;
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;
end;
2.客戶端連接到服務器後,發送一個或多個流,當斷開的時候,服務器將所有流合並在一起接收。
{*------------------------------------------------------------------------------
客戶端發送流,假定還未建立連接
------------------------------------------------------------------------------*}
procedure TClientForm.Button3Click(Sender: TObject);
var s: string; stream: TStream;
begin
IdTCPClient1.Connect;
try
s := 'Hello world!';
stream := TStringStream.Create(s);
IdTCPClient1.OpenWriteBuffer;
IdTCPClient1.WriteStream(stream, true);
finally
IdTCPClient1.CloseWriteBuffer;
stream.Free;
IdTCPClient1.Disconnect;
end;
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,-1,true);//當斷開連接時候接收流
stream.Position := 0;
Memo1.Lines.LoadFromStream(stream);
end;
end;