Delphi的Indy通訊中發送流檔案的注意事項

來源:互聯網
上載者:User

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

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;

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.