PDA

View Full Version : How to read only a certain amount of bytes



Morea
27th January 2009, 20:51
Hi.
I'm looking at the code of qt example "the fortune client", and they use the code



QString nextFortune;
in >> nextFortune;
to read a fortune from the socket, but what if they had got more data than that?
If the server sent two fortunes and the fortunes were broken down into little pieces and then received in some order, would the socket re-arrange the data so I get first one fortune and then the other one? I guess I'm a little clueless on network programming. I would assume that the networkstack is clever enough to put the pieces together in the right order before I read it from my Qt program, is it not?

But assuming that I only want to read the number of bytes that are given in the variable blocksize in the fortune client, how would I do that, even if there are more data waiting to be read? Assuming the fortune is stored as a Qstring (16 bit per char isn'it?) and then I really want to read data and put it back as a QString.

caduel
28th January 2009, 07:38
if you want to read a limited number of bytes: see QIODevice::read(qint64) (note that you might get less than that!)

If you write a QString to a QDataStream than reading it back in from a QDataStream (assuming that the you did not short read the package) will read just that string. The bytes behind will not become part of the string.
(As you don't (want to) know how Qt writes a QString to a QDataStream, reading a limited number of bytes does not help you here, btw)

On the other hand, the fortune server from the examples sends just one fortune and then disconnects. So the client does not have to worry about excess data.

HTH