Reputation: 679
I'm writing a program that sends files from a QT client over to an Android client.
A specific line of code writes the length-prefixed file name string to the stream maintained between them via the following code:
qDebug() << socket.write(QByteArray::number((qint32)fileName.length()));
I have casted fileName.length()
into a qint32
, yet for some reason the above code writes only 2 bytes to the socket's stream (i.e. the console window shows 2
from qDebug()
).
Is there any reason why?
Upvotes: 0
Views: 706
Reputation: 98495
The casting to qint32
is irrelevant and serves no purpose.
The QByteArray::number
creates an ASCII text representation of the number. In this case, the fileName.length()
had to have two digits and is between 10 and 99. Thus, the contents of the byte array are two ASCII digits. Note that the zero terminator is not included in the length()
or size()
of the array, and is thus not transmitted by the socket.
What you are transmitting is text, specifically a string that would be "21"
, had fileName.length()
been 21.
The code that does what you intend to do is:
QDataStream str(&socket);
str << (qint32)fileName.length();
The default byte order will be big-endian (network byte order). You can choose the other byte order:
str.setByteOrder(QDataStream::LittleEndian);
str << ...;
Upvotes: 2