QDataStream::operator>>(char *&) is expecting a 32 bit unsigned number of characters followed by that number of characters including the terminating nul byte. Here is a faked incoming packet and read:
#include <QCoreApplication>
#include <QByteArray>
#include <QBuffer>
#include <QDataStream>
#include <QDebug>
int main(int argc, char **argv)
{
// Fake data packet
out << "Payload";
qDebug() << "Bytes available" << packet.size() << packet.toHex();
// Fake socket
// your code
// need 4 bytes before this can work ---v
// look ahead for 32-bit string length, the overall block size is 4 bytes longer than the string
char buf[(int)sizeof(quint32)];
socket->peek(buf, sizeof(buf));
int blockSize = (*(buf+3) <<24) | (*(buf+2) <<16) | (*(buf+1) <<8) | *(buf);
blockSize += 4;
qDebug() << "Block size" << blockSize;
// we need to accumulate blockSize bytes before the following can work
char *data = 0;
in >> data;
qDebug() << (void *)data;
if (data)
qDebug() << "String:" << data;
delete[] data;
return 0;
}
#include <QCoreApplication>
#include <QByteArray>
#include <QBuffer>
#include <QDataStream>
#include <QDebug>
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
// Fake data packet
QByteArray packet;
QDataStream out(&packet, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_5);
out.setByteOrder(QDataStream::LittleEndian);
out << "Payload";
qDebug() << "Bytes available" << packet.size() << packet.toHex();
// Fake socket
QBuffer *socket = new QBuffer(&packet, qApp);
socket->open(QIODevice::ReadOnly);
// your code
QDataStream in(socket);
in.setVersion(QDataStream::Qt_5_5);
in.setByteOrder(QDataStream::LittleEndian);
// need 4 bytes before this can work ---v
// look ahead for 32-bit string length, the overall block size is 4 bytes longer than the string
char buf[(int)sizeof(quint32)];
socket->peek(buf, sizeof(buf));
int blockSize = (*(buf+3) <<24) | (*(buf+2) <<16) | (*(buf+1) <<8) | *(buf);
blockSize += 4;
qDebug() << "Block size" << blockSize;
// we need to accumulate blockSize bytes before the following can work
char *data = 0;
in >> data;
qDebug() << (void *)data;
if (data)
qDebug() << "String:" << data;
delete[] data;
return 0;
}
To copy to clipboard, switch view to plain text mode
Bookmarks