Question

I try to send a file via sendtext but i can't upload more than 4kb I send the file via base64 and a string:

ServerSocket1.Socket.Connections[listview1.Selected.index].Sendtext('FILE<-+^+->' + encodefile(edit4.text));

The encodefile script is:

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;

Under the 4kb it works perfect how can i fix this?

Was it helpful?

Solution

Like any other socket operation, SendText() is not guaranteed to transfer the entire requested data in a single operation, even when using the socket in blocking mode. The return value reports how many bytes, not characters were actually accepted. If the return value is smaller than your data, you have to call SendText() again for the remaining unsent data. So you need to call SendText() (actually, it is better to use SendBuf() directly) in a loop, eg:

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));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top