2.没人给程序?
用tcp或udp都可,只是用udp较tcp复杂.给出用tcp传送文件代码.
procedure TForm1.Send1_fileClick(Sender: TObject);
var ...
begin
OpenDialog1.Filter :='文本文件(*.txt)|*.txt|所有文件(*.*)|*.*';
if OpenDialog1.Execute then
begin
sendfilename:=OpenDialog1.FileName;
SendFStream := TFileStream.Create(OpenDialog1.FileName,fmOpenRead);
sendleft:=SendFStream.Size;
ClientSocket1.Address:=ip;
ClientSocket1.Open;
end;
end;
procedure TForm1.ClientSocket1Read(Sender: TObject;
Socket: TCustomWinSocket);
var s,s1: string;
buf: array [1..2048]of byte;//以2k大小为一个传送单位,大了可能出错
begin
s:=Socket.ReceiveText;//
if pos('go',s)<>0 then //开始发送
begin
if 2048<sendleft then
begin
SendFStream.ReadBuffer(buf,2048);
Socket.SendBuf(buf,2048);
sendleft:=sendleft-2048;
end
else
begin
SendFStream.ReadBuffer(buf,sendleft);
Socket.SendBuf(buf,sendleft);
SendFStream.Free;
end;
end;
end;
procedure TForm1.ClientSocket1Connect(Sender: TObject;
Socket: TCustomWinSocket);
begin
ClientSocket1.Socket.SendText(***);//文件名和长度
end;
procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var s,s1: string;
buf: array [1..2048]of byte;
begin
application.ProcessMessages;
if RecevFstream=nil then
begin
s:=socket.ReceiveText;
name_file:=get_filename
recevleft:=get_filesize;
RecevFstream:=TFileStream.Create(Get_FileName,fmCreate);
Socket.SendText('go');
end
else
begin
if 2048<recevleft then
begin
ALed2.Value:=true;
Socket.ReceiveBuf(buf,2048);
RecevFstream.WriteBuffer(Buf,2048);
recevleft:=recevleft-2048;
socket.SendText('go');
end
else
begin
socket.ReceiveBuf(buf,recevleft);
RecevFstream.WriteBuffer(Buf,sizeof(buf));
RecevFstream.Free;
RecevFstream:=nil;
end;
end;
end;