我在传送文件的时候,中途就会出现“传输异常终止”。只有在加入 sleep语句后,文件才能顺利传输(不计大小)。
但是这样会影响传输速度。
怎样才能在避免影响速度的情况下顺利传输文件?(最好像飞鸽那样的性能)
一下是代码//服务器端传文件函数
procedure TForm1.TCPTransFile(Socket: TSocket;filename:String);
Const BlockLen=1024*4;
var Ftrans:File of Byte;
Flen:Integer;
BlockNum,RemainLen:Integer;
BlockBuf:Array[0..BlockLen-1] of Byte;
i:Integer;
SendLen:Integer;
begin
AssignFile(Ftrans,filename);
Reset(Ftrans);
Flen:=FileSize(Ftrans);
BlockNum:=Flen div BlockLen;
progressBar1.Max := BlockNum+1;
RemainLen:=Flen mod BlockLen;
SendLen:=1;
for i:=0 to BlockNum-1 do
begin
if (SendLen<=0) then
Break;
BlockRead(Ftrans,BlockBuf[0],BlockLen);
SendLen:=send(Socket,BlockBuf,BlockLen,0);
sleep(1); //设置延时
progressBar1.Position := i;
Application.ProcessMessages;
end; if (SendLen<=0) then
begin
CloseFile(Ftrans);
TTY('传输异常终止!');
Exit;
end; if RemainLen>0 then
begin
BlockRead(Ftrans,BlockBuf[0],RemainLen);
SendLen:=send(Socket,BlockBuf,RemainLen,0);
if (SendLen<=0) then
begin
CloseFile(Ftrans);
TTY('传输异常终止!');
Exit;
end;
end;
CloseFile(Ftrans);
TTY('传输完成!');
end;//客户端接受文件
procedure TForm1.TCPClientData(Socket: TSocket);
Const BlockLen=1024*4;
var
Ftrans:File of Byte;
size,Recelen:Integer;
BlockBuf:Array[0..BlockLen-1] of Byte;
begin
AssignFile(Ftrans,filename);
Reset(Ftrans);
//移动文件指针到文件末尾
Seek(Ftrans,GetRecordCount(filename )); Recelen:=recv(Socket,BlockBuf,BlockLen,0); if (Recelen>0)then
begin
BlockWrite(Ftrans,BlockBuf[0],Recelen);
Application.ProcessMessages;
end;
CloseFile(Ftrans);
end;
但是这样会影响传输速度。
怎样才能在避免影响速度的情况下顺利传输文件?(最好像飞鸽那样的性能)
一下是代码//服务器端传文件函数
procedure TForm1.TCPTransFile(Socket: TSocket;filename:String);
Const BlockLen=1024*4;
var Ftrans:File of Byte;
Flen:Integer;
BlockNum,RemainLen:Integer;
BlockBuf:Array[0..BlockLen-1] of Byte;
i:Integer;
SendLen:Integer;
begin
AssignFile(Ftrans,filename);
Reset(Ftrans);
Flen:=FileSize(Ftrans);
BlockNum:=Flen div BlockLen;
progressBar1.Max := BlockNum+1;
RemainLen:=Flen mod BlockLen;
SendLen:=1;
for i:=0 to BlockNum-1 do
begin
if (SendLen<=0) then
Break;
BlockRead(Ftrans,BlockBuf[0],BlockLen);
SendLen:=send(Socket,BlockBuf,BlockLen,0);
sleep(1); //设置延时
progressBar1.Position := i;
Application.ProcessMessages;
end; if (SendLen<=0) then
begin
CloseFile(Ftrans);
TTY('传输异常终止!');
Exit;
end; if RemainLen>0 then
begin
BlockRead(Ftrans,BlockBuf[0],RemainLen);
SendLen:=send(Socket,BlockBuf,RemainLen,0);
if (SendLen<=0) then
begin
CloseFile(Ftrans);
TTY('传输异常终止!');
Exit;
end;
end;
CloseFile(Ftrans);
TTY('传输完成!');
end;//客户端接受文件
procedure TForm1.TCPClientData(Socket: TSocket);
Const BlockLen=1024*4;
var
Ftrans:File of Byte;
size,Recelen:Integer;
BlockBuf:Array[0..BlockLen-1] of Byte;
begin
AssignFile(Ftrans,filename);
Reset(Ftrans);
//移动文件指针到文件末尾
Seek(Ftrans,GetRecordCount(filename )); Recelen:=recv(Socket,BlockBuf,BlockLen,0); if (Recelen>0)then
begin
BlockWrite(Ftrans,BlockBuf[0],Recelen);
Application.ProcessMessages;
end;
CloseFile(Ftrans);
end;
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货