我用udp写了个简单的文件传输,我是看别人的例子写的,不知道为什么会丢包,传文件的时候接收的文件总是比实际发送的文件要少几十kb。
代码如下服务器的:
unit server_Unit1;interfaceuses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, IdBaseComponent, IdComponent, IdUDPBase, IdUDPServer,IdSocketHandle,
  StdCtrls;type
  TForm1 = class(TForm)
    IdUDPServer1: TIdUDPServer;
    ListBox1: TListBox;
    procedure IdUDPServer1UDPRead(Sender: TObject; AData: TStream;
      ABinding: TIdSocketHandle);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;var
  Form1: TForm1;
  f:TFileStream;
implementation{$R *.dfm}procedure TForm1.IdUDPServer1UDPRead(Sender: TObject; AData: TStream;
  ABinding: TIdSocketHandle);
begin
Adata.Seek(0,0);
f.CopyFrom(Adata,Adata.Size);
self.ListBox1.Items.Add(inttostr(f.Position));
end;procedure TForm1.FormCreate(Sender: TObject);
begin
f:=Tfilestream.Create('c:\111.txt',fmcreate);
end;end.客户端的:
unit client_Unit1;interfaceuses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, IdBaseComponent, IdComponent, IdUDPBase, IdUDPClient, StdCtrls;type
  TForm1 = class(TForm)
    IdUDPClient1: TIdUDPClient;
    OpenDialog1: TOpenDialog;
    Button1: TButton;
    ListBox1: TListBox;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;var
  Form1: TForm1;
  fstream:TFilestream;
  i,len:integer;
  sendx:array[0..1023] of byte;
implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);
begin
self.IdUDPClient1.Active:=true;
if self.OpenDialog1.Execute then
begin
fstream:=TFilestream.Create(self.OpenDialog1.FileName,fmOpenRead);
i:=0;
len:=1024;
while i<fstream.Size do
begin
if fstream.Size-i<len then
begin
len:= fstream.Size-i;
end;
fstream.Read(sendx,len);
self.IdUDPClient1.SendBuffer(sendx,len);
self.ListBox1.Items.Add(inttostr(fstream.Position));
inc(i,len);
end;
end;
end;end.

解决方案 »

  1.   

    udp本身就是不可靠的协议。
    你要用udp来传输文件的话,就需要自己在应用层做可靠性保证。
      

  2.   

    那也不至于 这么丢包吧,,可是别人用udp写的都没问题啊...我感觉是我程序的问题..期待高手帮助
    .....
      

  3.   

    udp每次只能够发一定大小的数据
      

  4.   

    UDP传输文件要注意的1、对ADatA每次接收到数据后将POSIONTION归零。2、由于UDP本身的传输的不可靠性,你需要做的是对于数据包的大小的控制和数据完整性的检测