UDP下如何采用内存流进行传输?(50分)

  • 主题发起人 主题发起人 夏敏
  • 开始时间 开始时间

夏敏

Unregistered / Unconfirmed
GUEST, unregistred user!
UDP下如何采用内存流进行传输?举个例子
 
楼主要用什么UDP控件呢?
 
UDP实际上不适合进行大数据的传输
如果你确定要这么做,
C:先发数据长度,再发数据(可以是流)
S:数据到达时先读数据长度,然后将数据读到流中
 
Dephi安装目录FastNet有自带的Demo,就是使用内存流传输的
 
//我自己写了一个,在本机进行测试,传输35M的文件没有问题。

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, IdBaseComponent, IdComponent, IdUDPBase, IdUDPServer, StdCtrls,
IdUDPClient,IdSocketHandle, ComCtrls;

type
TForm1 = class(TForm)
UDPServer: TIdUDPServer;
UDPClient: TIdUDPClient;
LBHotname: TLabel;
LBhostAdress: TLabel;
Label3: TLabel;
Label4: TLabel;
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
Edit1: TEdit;
ProgressBar1: TProgressBar;
procedure Button1Click(Sender: TObject);
procedure UDPServerUDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
FS: TFileStream;
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
LBHotname.Caption := UDPServer.LocalName;
LBhostAdress.Caption :=IntToStr(UDPServer.DefaultPort);
end;

procedure TForm1.UDPServerUDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
var
S :String;
begin
if AData.Size > 0 then
begin
FS.CopyFrom(AData,AData.Size);
S := IntToStr(AData.Size);
ABinding.SendTo(ABinding.PeerIP,ABinding.PeerPort,S[1],length(S));
end;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
F: TFileStream;
Fbuffer :array[0..1023] of Byte;
ct,recv:integer;
begin
F := TFileStream.Create('F:/QQ/Wrox - Professional C# (C#高级编程).pdf',fmOpenRead);
F.Seek(0,soBeginning);
ProgressBar1.Max := F.Size;
ProgressBar1.Min := 0;
ct := 0;
repeat
ct := F.Read(Fbuffer,1024);
if ct > 0 then
begin
recv := 0;
UDPClient.SendBuffer(Fbuffer,1024);
while recv < ct do
begin
Application.ProcessMessages;
try
recv := recv + StrToInt(UDPClient.ReceiveString());
except
end;
end;
end;
ProgressBar1.Position := ProgressBar1.Position + ct;
until ct = 0;
F.Free;

end;

procedure TForm1.FormCreate(Sender: TObject);
begin
FS := TFileStream.Create(Edit1.Text,fmCreate or fmOpenReadWrite);
UDPServer.Active := True;
UDPClient.Active := True;
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FS.Free;
end;

end.
 
后退
顶部