用Delphi编写点对点传文件程序(2)

Delphi教程 2025-08-12

end;

end;

cs.OnRead(Sender: TObject;Socket: TCustomWinSocket);

var

sTemp:string;

bufSend:pointer;

begin

sRecv:=Socket.ReceiveText;

Case sRecv[1] of

MP_REFUSE:ShowMessage('Faint,be refused!');

MP_ACCEPT:begin

fsSend:=TFileStream.Create(OpenDialog1.FileName,fmOpen);

//iBYTEPERSEND是个常量,每次发送包的大小。

Socket.SendText(MP_FILEPROPERTY+Trunc(fsSend.Size/iBYTEPERSEND)+1);

end;

MP_NEXTWILLBEDATA:begin

Socket.SendText(MP_NEXTWILLBEDATA);

end;

MP_DATA:begin

try

GetMem(bufSend,iBYTEPERSEND+1);

if (fsSend.Position+1+iBYTEPERSEND) <  fsSend.Size then

begin

fsSend.Read(bufSend^,iBYTEPERSEND);

Socket.SendBuf(bufSend^,iBYTEPERSEND);

fsSend.Free;

end//普通的发送,大小为iBYTEPERSEND

else begin

fsSend.Read(bufSend^,fsSend.Size-fsSend.Position-1);

Socket.SendBuf(bufSend^,fsSend.Size-fsSend.Position-1);

end;//最后一次发送,发送剩余的数据

finally

FreeMem(bufSend,iBYTEPERSEND+1);

end;{of try}

end;

MP_ABORT:begin

//被取消了:(

fsSend.Free;

end;

end;{of case}

end;

整理程序:

 加入错误判断,优化程序,把Server和Client联合在一起,加入剩余时间进度显示,做成能一次传多个文件,加入聊天功能,就成了一个很好的点对点传文件的程序。