user769398
user769398

Reputation:

Problem with QTcpSocket and sending binary data

There is following code:

QFile in("c:\\test\\pic.bmp");
in.open(QFile::ReadOnly);
QByteArray imageBytes = in.readAll();
socket->write(bytesToSend);

On server, i'm receiving only header of .bmp file. What could cause such behavior? And How to solve this problem?

Upvotes: 0

Views: 3023

Answers (1)

Oleg
Oleg

Reputation: 798

This method writes at most number of bytes which is your data size. But can actually write less. It actually returns number of bytes sent. So you should make a loop sending the rest of data until everything is sent. Like this.

qint64 dataSent = 0;
while(dataSent < sizeof(bytesToSend))
{
   qint64 sentNow = socket->write(bytesToSend+dataSent);
   if(sentNow >= 0)
      dataSent += sentNow;
   else
      throw new Exception();
}

This is a native socket behavior.

Upvotes: 2

Related Questions