程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> Delphi的Indy通信中發送流文件的注意事項

Delphi的Indy通信中發送流文件的注意事項

編輯:Delphi

客戶端發送流到服務器端有幾種方式,這裡討論兩種:

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;

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved