How to transfer data using Indy TCP Server/Client?

Viewed 4549

I want to transfer data from the TIdTCPServer to the TIdTCPClient.

On the server side I have:

procedure TForm1.IdTCPServer1Execute(AContext: TIdContext);
var x:Integer;
    Received:String;
    SendBuff:TBytes;
    hFile:THandle;
    fSize:Int64;
begin
 fSize:=0;
 if MOpenFileForRead(hFile,MGetExePath+'\test.jpg') then begin
  fSize:=MFileSize(hFile);
  SetLength(SendBuff,fSize);
  MReadFile(hFile,SendBuff[0],fSize);
  MCloseFile(hFile);
 end;

 // ... here the SendBuff contains valid data, I checked. 

 repeat
  Received:=AContext.Connection.Socket.ReadLn;
  if not AContext.Connection.Connected then Exit;
  if Received=CMD_TEST_FILE then begin
   AContext.Connection.Socket.Write(fSize);
   AContext.Connection.Socket.WriteBufferOpen;
   AContext.Connection.Socket.Write(SendBuff);
   AContext.Connection.Socket.WriteBufferClose;
  end;
 until False;
end;

And the client side:

procedure TForm1.Button2Click(Sender: TObject);
var fSize:Int64;
    RecvBuff:TBytes;
    hFile:THandle;
begin
  IdTCPClient1.Socket.WriteLn(CMD_TEST_FILE);
  fSize:=IdTCPClient1.Socket.ReadInt64;
  SetLength(RecvBuff,fSize);
  IdTCPClient1.Socket.ReadBytes(RecvBuff,fSize);
  if MCreateFile(hFile, MGetExePath+'\new.jpg') then begin
   MWriteFile(hFile,RecvBuff[0],fSize);
   MCloseFile(hFile);
  end;
  Memo1.Lines.Add('ok');
end;

... but it's not working. I checked the read and write data functions used and they are ok. At the server the buffer is set ok, the file size arrives at client ok, but the content of the buffer at client is only zeros.

P.S: I want to send the file in this way not with stream or anything else.

1 Answers
Related