用TServerSocket和TClientSocket做的简单的发送接受例程:
发送:
var
buffer: string; // 保存要发送的文件内容
currentpos: cardinal = 0; // 当前发送起始位置,这两个变量为全局变量
restlen: Integer = 0; // 剩余需要发送的长度
procedure TForm1.SendFile(const filename: string);
var
fid: integer;
begin
fid := fileopen(filename, fmOpenRead or fmShareDenyNone);
if fid > 0 then
begin
setlength(buffer, fileseek(fid, 0, 2));
fileseek(fid, 0, 0);
fileread(fid, buffer[1], length(buffer)); // 读取文件到内存
fileclose(fid);
currentpos := cardinal(buffer)-4; // 设定发送起始位置,初始值为buffer的地址-4(delphi的string类型起始地址-4的位置
// 正好存储了string的长度,我们将长度一起发以便server判断是否接受完整
restlen := length(buffer)+4; // 剩余需要发送的长度
clientsocket1.onwrite := continuesendfile;
clientsocket1.onerror := sendfilestop;
continuesendfile(self, clientsocket1.socket); // 首次发送
end;
procedure TForm1.ContinueSendFile(Sender: TObject; Socket: TCustomWinSocket);
var
l: Integer;
begin
if restlen > 0 then
repeat // 循环发送直到填满发送缓冲区或全部发完
l := socket.sendbuf(pbyte(currentpos)^,restlen);
if l > 0 then
begin
inc(currentpos,l);
dec(restlen, l);
end;
until (l<0) or (restlen=0);
end;
procedure TForm1.SendFileStop(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
restlen := 0; // 终止发送
ErrorCode := 0; // 防止弹出错误窗口
end;
接收:
var
buffer: string;
procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
fid: integer;
begin
buffer := buffer + socket.receivetext;
if (length(buffer)>4) and (length(buffer)=pinteger(integer(buffer))^+4) then //接收完成
begin
fid := filecreate('received.txt');
filewrite(fid,pbyte(integer(buffer)+4)^, pinteger(integer(buffer))^);
fileclose(fid);
buffer := '';
end;
end;