TimC
TimC

Reputation: 313

read/write raw data with QDataStream

I am fairly new to QDataStream and Socket programming, and what I want to do is to simply send a quint32 header value (four bytes) from client to host. But I am having some trouble with QDataStream.

QByteArray data;
QDataStream ds(&data, QIODevice::ReadWrite);
int a = htonl(32);
char *head = (char*)&a;
for(int i=0;i<4;i++)
    qDebug() << QString::number(int((head[i]&0xff))+0x100, 16) << " ";
qDebug() << endl;

here, the output is "100 100 100 120", which is what I want. Then I try to write it into data stream.

ds.writeRawData(head, 4);
char *buffer = new char[4];
ds.readRawData(buffer, 4);
for(int i=0;i<4;i++)
    qDebug() << QString::number(int((buffer[i]&0xff))+0x100, 16) << " ";
qDebug() << endl;

But here the output here is "100 100 100 100"

Am I having some misunderstanding about the usage of QDataStream?

Upvotes: 6

Views: 20808

Answers (1)

Arnold Spence
Arnold Spence

Reputation: 22292

You should reset the position of the stream device by calling ds.device()->reset(); before you attempt to read the data with ds.readRawData().

ds.readRawData() will return the number of bytes that were read. If you check it, it is probably returning 0.

Upvotes: 8

Related Questions