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 suc开发者_JS百科h behavior? And How to solve this problem?
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.
精彩评论