you can assume that you size can be stored in 32-bit (4 byte) long int - you can use qint32 (or even quint32 - size can't be less then 0).
so you have to convert quint32 into QByteArray, writing there byte by byte of your quint32, something like this:
quint32 size = ...; // your size
for (int i = 0; i < 4; ++i) {
quint8 b = (size >> (i*8)) & 0x000000ff;
intBytes.append(b);
}
quint32 size = ...; // your size
QByteArray intBytes;
for (int i = 0; i < 4; ++i) {
quint8 b = (size >> (i*8)) & 0x000000ff;
intBytes.append(b);
}
To copy to clipboard, switch view to plain text mode
on the client side you have to create a valid quint32 from a byte array:
QByteArray intBytes
= socket.
read(4);
// 4*8 = 32 bits quint32 size = 0; // init with 0 to be sure there is really 0
for (int i = 0; i < 4; ++i) {
quint8 b = intBytes.at(i);
size |= (((quint32)b) & 0x000000ff) << i*8;
}
QByteArray intBytes = socket.read(4); // 4*8 = 32 bits
quint32 size = 0; // init with 0 to be sure there is really 0
for (int i = 0; i < 4; ++i) {
quint8 b = intBytes.at(i);
size |= (((quint32)b) & 0x000000ff) << i*8;
}
To copy to clipboard, switch view to plain text mode
(should work but i did not check so try to print the int first to see if it is what you have sent :])
now you have the size, so whenever readyRead() comes from socket you have to check int the slot if you have to start reading new image (read size and some of data) or you are in the middle of image data. Whenever you read image data just check if bytesAvailable() are equal to the needed size, if less than readAll() and decrease size by a number of bytes you already read. and so on... In other words reading data becomes a little state machine :] so you have to react adequately to the state you are in.
P.S. And it is nice to check if file was opened succesfully, so instead of this:
file.open(QIODevice::ReadOnly);
To copy to clipboard, switch view to plain text mode
better do it like this:
// do something proper if cannot open file, e.g.:
qDebug("Cannot open file!");
return;
}
if (!file.open(QIODevice::ReadOnly)) {
// do something proper if cannot open file, e.g.:
qDebug("Cannot open file!");
return;
}
To copy to clipboard, switch view to plain text mode
Bookmarks