接收端
procedure TFormServer.ServerSocket1ClientRead(Sender: TObject; Socket: TCustomWinSocket);
var
buf: array [1..2048] of char;
rcvtxt, FName: string;
left, IPIndex: integer;
begin
IPIndex := IPSL.IndexOf(Socket.RemoteAddress);
if IPIndex < 0 then
Exit;
try //要控制客户端发完了文件后才能再发送其它信息,否则认为是文件信息,会被写入文件
if FileRec[IPIndex].FileName = '' then
begin
rcvtxt := Socket.ReceiveText;
if Copy(rcvtxt, 1, Length(_GetFileName)) = _GetFileName then //取文件名
begin
FName := Copy(rcvtxt, Pos('-', rcvtxt) + 1, Length(rcvtxt));
if FileExists(SavePath + FName) then
Socket.SendText(_FileExists) //发送文件存在标志
else
Socket.SendText(_NotFileExists);//发送文件不存在标志
end
else //发送文件名和大小
begin
FileRec[IPIndex].Size := StrToIntDef(Copy(rcvtxt, 1, Pos('-', rcvtxt) - 1), 0);
FileRec[IPIndex].Count := 0;
if Not DirectoryExists(SavePath) then
ForceDirectories(SavePath);
FileRec[IPIndex].FileName := SavePath + copy(rcvtxt, Pos('-', rcvtxt) + 1, Length(rcvtxt));
AssignFile(FileRec[IPIndex].TargetFile, FileRec[IPIndex].FileName);
Rewrite(FileRec[IPIndex].TargetFile, 1);
FileRec[IPIndex].LinesIndex := MemoReport.Lines.Count - 1;
Socket.SendText(_AllowSend); //响应一块
end;
end
else
begin
left := FileRec[IPIndex].Size - FileRec[IPIndex].Count; //未写的字节数
if sizeof(buf) < left then //满一块则写一块
begin
Socket.ReceiveBuf(buf, sizeof(buf));
BlockWrite(FileRec[IPIndex].TargetFile, buf, sizeof(buf));
FileRec[IPIndex].Count := FileRec[IPIndex].Count + sizeof(buf);
Socket.SendText(_AllowSend);
end
else //否则写剩余字节数
begin
Socket.ReceiveBuf(buf,left);
BlockWrite(FileRec[IPIndex].TargetFile,buf,left);
CloseFile(FileRec[IPIndex].TargetFile);
FileRec[IPIndex].FileName := '';
end;
end;
except
end;
end;