U_Client.pas
资源名称:网络文件传输原代码.rar [点击查看]
上传用户:lzzxgs
上传日期:2013-03-15
资源大小:474k
文件大小:2k
源码类别:
P2P编程
开发平台:
Delphi
- unit U_Client;
- interface
- uses
- Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
- Dialogs, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, Math,
- StdCtrls, ComCtrls;
- type
- Tfrm_Client = class(TForm)
- SaveDialog1: TSaveDialog;
- IdTCPClient1: TIdTCPClient;
- Button1: TButton;
- StatusBar1: TStatusBar;
- Edit1: TEdit;
- Label1: TLabel;
- Edit2: TEdit;
- Label2: TLabel;
- procedure Button1Click(Sender: TObject);
- private
- { Private declarations }
- public
- { Public declarations }
- end;
- var
- frm_Client: Tfrm_Client;
- implementation
- {$R *.dfm}
- procedure Tfrm_Client.Button1Click(Sender: TObject);
- var
- cmd: string;
- ASize, TotalSize: Int64;
- AFileStream: TFileStream;
- begin
- IdTCPClient1.Host := Edit1.Text; //连接主机
- IdTCPClient1.Port := StrToIntDef(Edit2.Text, 9925); //端口
- IdTCPClient1.Connect; //连接
- try
- IdTCPClient1.WriteLn('BEGIN'); //提示服务器开始接收
- cmd := IdTCPClient1.ReadLn;
- //以“|”符号分离文件名
- SaveDialog1.FileName := Copy(cmd, Pos('|', cmd) + 1, Length(cmd));
- if not SaveDialog1.Execute then
- begin
- IdTCPClient1.WriteLn('CANCEL'); //告诉服务器取消
- IdTCPClient1.Disconnect; //断开连接
- exit;
- end;
- TotalSize := StrToInt(Copy(cmd, 0, Pos('|', cmd) - 1)); //分离文件大小
- //建立文件流准备接收
- AFileStream := TFileStream.Create(SaveDialog1.FileName, fmCreate);
- try //循环开始接受
- repeat
- IdTCPClient1.WriteLn(IntToStr(AFileStream.Size));//发送当前传输的位置
- ASize := Min(TotalSize - AFileStream.Size, IdTCPClient1.RecvBufferSize);
- //选择剩余大小和缓冲区大小小的一个作为传输的大小
- IdTCPClient1.ReadStream(AFileStream, ASize); //接收流
- StatusBar1.SimpleText := Format('当前传输位置%d/大小%d', [AFileStream.Size, TotalSize]);
- Application.ProcessMessages;
- until AFileStream.Size = TotalSize; //大小一致了表示结束
- finally
- AFileStream.Free; //释放文件流
- end;
- IdTCPClient1.WriteLn('END'); //提示服务器传输完成
- StatusBar1.SimpleText := '传输完成...';
- except
- StatusBar1.SimpleText := '连接服务器失败或者对方已经中断传输!';
- end;
- IdTCPClient1.Disconnect;
- end;
- end.