QDataStream and readBytes
Hi,
In the wake of this thread thread I'm trying to read binary data from a socket, hence the code:
Code:
unsigned int totalBytes = 0;
totalBytes = tcpSocket.bytesAvailable();
if (totalBytes < 4) return; // bogus tx...
uint headerSize=sizeof(uint);
char * header = new char [headerSize];
uint headerBytes=0;
inData.readBytes(header, headerSize);
headerBytes=atoi(header);
Unless I really don't know what I'm doing... ;) (most probably) why does inData.readBytes(header, headerSize); always cause a segfault?
Any pointers welcome.
Thanks in advance,
Pedro Doria Meunier.
Re: QDataStream and readBytes
Use QDataStream::readRawData(). readBytes() is a complement of writeBytes() and it assumes that the data is in certain format (it also allocates the buffer itself).
Won't it be simplier to write:
Code:
uint headerBytes=0;
inData >> headerBytes;
?
Re: QDataStream and readBytes
Txs Jacek,
I already tried that only to discover that these devices are stupid enough to send the header and data all at once, so in >> is not an option. I have to read the 1st bytes of what comes to determine the length of the following data... :(
Kind regards,
Pedro Doria Meunier.
Re: QDataStream and readBytes
Quote:
Originally Posted by
pdoria
I already tried that only to discover that these devices are stupid enough to send the header and data all at once, so in >> is not an option.
Why?
Code:
quint16 header;
inData >> header;
will read exactly two bytes from the stream into header, leaving the rest intact. Then you can check the header and read more data.
Re: QDataStream and readBytes
Jacek,
You're absolutely right. This is working now. I don't remember what I did last time... :o
Man... what a ride!!! :D
I sincerely want to thank you for your valuable support... thank you!
Kind regards,
Pedro Doria Meunier.
Re: QDataStream and readBytes
Ok. last step:
this doesn't work...
Code:
quint16 dataLength=0;
while (zerocount < 4 && dataLength==0)
{
inData >> dataLength;
if (dataLength==0) zerocount++;
}
// exceed number of tries... bogus txs. return.
if (zerocount==3) return;
char * data = new char[dataLength];
inData >> data;
the data is always 0x0 ... :confused:
So ... please tell me... after in >> dataLength the pointer in the stream is advanced or not?
the operator>> ( char *& s ) is able to convert the binary data into char?
Thanks in advance.
Re: QDataStream and readBytes
bump.
Must one do this?
Code:
char * data = new char[dataLength];
qint8 c;
int n;
for (n=0; n<dataLength; n++) {
inData >> c;
data[n]=c;
}
It feels a bit archaic...
Re: QDataStream and readBytes
Quote:
Originally Posted by
pdoria
Must one do this?
No, you can use readRawData() instead.
Re: QDataStream and readBytes
Be aware that QDataStream is not a general purpose binary stream but a serialization method. Don't use it if you don't need it.