开发者

QDataStream readSlot termination symbol

at the moment My socket conversation is text based. I end all my conversation end with a ; and some conversations are binary. now I've decided to make all my conversations binary. and I开发者_开发知识库 want to use QDataStream as the socket wrapper. so what measures should I take in place of ; usage.

e.g. i used to check for the ; at the end. when readyRead was emitted. now I think I'll put the buffer size at the begening of the buffer. but the problem is when I get some incomplete buffer. can I parse the size ?


Neel, I'd recommend you the following: QDataStream has convenient overloaded "operator>>" and "operator<<". What I usually do in such case is define the size of the data to be, for example, first 4 bytes of the stream. And on the other end I expect those 4 bytes to be read to determine the whole data size.

For example some pseudo code (C++ style but just gives and idea what you need rather than 100% polished and working code):

QByteArray myData = getData();
QDataStream ds(&socket);

ds << myData.size();
// Note: here your data will be encoded and be '\0' terminated
ds << myData.constData(); 

// so you might want to consider this call
// although since Qt doesn't guarantee exactly myData.size bytes to be written
// its your responsibility to check whether everything is written
ds.writeRawData(myData.constData(), myData.size());

Now, if you use QByteArray or any of the Qt types that can be sent through QDataStream, you can take advantage of what is already implemented in Qt and send your data as simple as:

QByteArray myData = getData();
QDataStream ds(&socket);
ds << myData;

In this case just check here http://doc.qt.nokia.com/4.7/datastreamformat.html of how Qt writes QByteArray to QDataStream. Even more: if you have QDataStream on the second end, all you need to do is just read your data as easy as you wrote it.

Hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜