[Interest] How to send an arbitrary file over sockets

Thiago Macieira thiago.macieira at intel.com
Sat May 30 02:48:12 CEST 2020


On Friday, 29 May 2020 16:29:13 PDT Ghobad Zarrinchian wrote:
> Dear all,
> I'm writing a client/server application in which the client can send a file
> to the server. At the client side, my code is something like below:
> 
> QFile fl(file_name);
> 
> fl.open(QIODevice::ReadOnly);
> 
> QByteArray fileBytes = fl.readAll();
> 
> socket->write(fileBytes);
> 
> fl.close();
> 
> And at the server side, the code that receives the file is something like
> this:
> 
> QByteArray data = client_socket->readAll();
> QFile fl(file_name);fl.open(QIODevice::WriteOnly);fl.write(data);fl.close();
> 
> While the code above works well with text files, it does not work for
> other file types (like JPG and PDF files). What is the problem? How
> should i modify the code so that it works for all kinds of files?

Most likely you didn't wait for the socket to finish receiving everything 
before you called readAll(). Insert a waitForDisconnected() before that 
readAll() and you should receive just fine.

Alternatively, and probably better, you could write to the file after every 
readyRead() is emitted. That eliminates the need to buffer the entire file in 
memory on the receiver side, while receiving.

Avoiding the buffering on the sender side is let as an exercise for the 
reader.

-- 
Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel System Software Products





More information about the Interest mailing list