Delphi的Indy通信中发送流文件的注意事项
客户端发送流到服务器端有几种方式,这里讨论两种:
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;
|
||
Everyday is lonely day. |
|