今天我們介紹用Delphi寫一個簡單的P2P文件傳輸,一方發送文件,一方接受,直到傳輸完整個文件。本文主要介紹客戶端部分的實現,客戶端的運行效果如圖所示:
網絡文件傳輸程序客戶端完整代碼:
01
unit
U_ClIEnt;
02
interface
03
uses
04
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
05
Dialogs, IDBaseComponent, IdComponent, IdTCPConnection, IdTCPClIEnt, Math,
06
StdCtrls, ComCtrls;
07
type
08
Tfrm_ClIEnt =
class
(TForm)
09
SaveDialog1: TSaveDialog;
10
IdTCPClient1: TIdTCPClIEnt;
11
Button1: TButton;
12
StatusBar1: TStatusBar;
13
Edit1: TEdit;
14
Label1: TLabel;
15
Edit2: TEdit;
16
Label2: TLabel;
17
procedure
Button1Click(Sender: TObject);
18
private
19
{ Private declarations }
20
public
21
{ Public declarations }
22
end
;
23
var
24
frm_Client: Tfrm_ClIEnt;
25
implementation
26
{$R *.dfm}
27
Tfrm_ClIEnt
.
28
29
cmd:
string
30
ASize, TotalSize:
Int64
31
AFileStream: TFileStream;
32
begin
33
IdTCPClIEnt1
Host := Edit1
Text;
//連接主機
34
Port := StrToIntDef(Edit2
Text,
9925
);
//端口
35
Connect;
//連接
36
try
37
WriteLn
(
'BEGIN'
//提示服務器開始接收
38
cmd := IdTCPClIEnt1
ReadLn;
39
//以“|”符號分離文件名
40
SaveDialog1
FileName := Copy(cmd, Pos(
'|'
, cmd) +
1
, Length(cmd));
41
if
not
Execute
then
42
43
'CANCEL'
//告訴服務器取消
44
Disconnect;
//斷開連接
45
exit;
46
47
TotalSize := StrToInt(Copy(cmd,
0
, Pos(
, cmd) -
));
//分離文件大小
48
//建立文件流准備接收
49
AFileStream := TFileStream
Create(SaveDialog1
FileName, fmCreate);
50
//循環開始接受
51
repeat
52
(IntToStr(AFileStream
Size));
//發送當前傳輸的位置
53
ASize := Min(TotalSize - AFileStream
Size, IdTCPClIEnt1
RecvBufferSize);
54
//選擇剩余大小和緩沖區大小小的一個作為傳輸的大小
55
ReadStream(AFileStream, ASize);
//接收流
56
StatusBar1
SimpleText := Format(
'當前傳輸位置%d/大小%d'
, [AFileStream
Size, TotalSize]);
57
Application
ProcessMessages;
58
until
AFileStream
Size = TotalSize;
//大小一致了表示結束
59
finally
60
Free;
//釋放文件流
61
62
'END'
//提示服務器傳輸完成
63
SimpleText :=
'傳輸完成...'
64
except
65
'連接服務器失敗或者對方已經中斷傳輸!'
66
67
68
69
本例效果圖: 代碼文件:unit Unit1;inter
之前已經有了兩種多線程的同步方法:Critic
DrawLine(); DrawLines(); Draw
Delphi寫的輕型鍵盤打字游戲代碼,練習打字用著不錯,代