我尝试通过sendtext发送文件,但我无法上传超过4kb 我通过base64和字符串发送文件:
ServerSocket1.Socket.Connections[listview1.Selected.index].Sendtext('FILE<-+^+->' + encodefile(edit4.text));
encodefile脚本是:
function EncodeFile(const FileName: string): AnsiString;
var
stream: TMemoryStream;
begin
stream := TMemoryStream.Create;
try
stream.LoadFromFile(Filename);
result := EncodeBase64(stream.Memory, stream.Size);
finally
stream.Free;
end;
end;
在4kb下它的完美工作如何解决这个问题?
答案 0 :(得分:2)
与任何其他套接字操作一样,SendText()
无法保证在单个操作中传输整个请求的数据,即使在阻塞模式下使用套接字也是如此。返回值报告实际接受了多少字节,而不是字符。如果返回值小于您的数据,则必须再次为剩余的未发送数据调用SendText()
。因此,您需要在循环中调用SendText()
(实际上,最好直接使用SendBuf()
),例如:
uses
..., ScktComp, Winsock;
function SendTextToSocket(Socket: TCustomWinSocket; const S: AnsiString): Boolean;
var
Data: PAnsiChar;
DataLen, Sent: Integer;
begin
Result := False;
Data := PAnsiChar(S);
DataLen := Length(S);
while DataLen > 0 do
begin
Sent := Socket.SendBuf(Data^, DataLen);
if Sent = SOCKET_ERROR then
begin
if WSAGetLastError <> WSAEWOULDBLOCK then
Exit;
end
else if Sent = 0 then
begin
Exit;
end else
begin
Inc(Data, Sent);
Dec(DataLen, Sent);
end;
end;
Result := True;
end;
SendTextToSocket(ServerSocket1.Socket.Connections[ListView1.Selected.Index], 'FILE<-+^+->' + EncodeFile(Edit4.Text));