QDataStream和QByteArray

一个写操作可以参考:

QDataStream &operator >>(QDataStream &in, SerializedMessage &message)
{
   qint32 type;
  qint32 dataLength;
  QByteArray dataArray;
  in >> type >> dataLength;
  dataArray.resize(dataLength);  // <-- You need to add this line.
  int bytesRead = in.readRawData(dataArray.data(), dataLength);
  // Rest of function goes here.
}

 

void SomeClass::slotReadClient() { // slot connected to readyRead signal of QTcpSocket
    QTcpSocket *tcpSocket = (QTcpSocket*)sender();
    while(true) {
        if (tcpSocket->bytesAvailable() < 4) {
           break;
        }
        char buffer[4]
        quint32 peekedSize;
        tcpSocket->peek(buffer, 4);
        peekedSize = qFromBigEndian<quint32>(buffer); // default endian in QDataStream
        if (peekedSize==0xffffffffu) // null string
           peekedSize = 0;
        peekedSize += 4;
        if (tcpSocket->bytesAvailable() < peekedSize) {
           break;
        }
        // here all required for QString  data are available
        QString str;
        QDataStream(tcpSocket) >> str;
        emit stringHasBeenRead(str);
     }
}

 

QString占两字节,转成一个字节可以用toUtf8()。
Per the Qt serialization documentation page, a QString is serialized as:

- If the string is null: 0xFFFFFFFF (quint32)
- Otherwise:  The string length in bytes (quint32) followed by the data in UTF-16.
If you don't like that format, instead of serializing the QString directly, you could do something like

stream << str.toUtf8();
How I can remove it, including last null byte?
You could add the string in your preferred format (no NUL terminator but with a single length header-byte) like this:

const char * hello = "hello";
char slen = strlen(hello);
stream.writeRawData(&slen, 1);
stream.writeRawData(hello, slen);
QVariantMap myMap, inMap;
QByteArray mapData;

myMap.insert("Hello", 25);
myMap.insert("World", 20);

QDataStream outStream(&mapData, QIODevice::WriteOnly);
outStream << myMap;
qDebug() << myMap;
QDataStream inStream(&mapData, QIODevice::ReadOnly);
inStream >> inMap;
qDebug() << inMap;

 

posted @ 2016-12-08 17:14  IT由零开始  阅读(8245)  评论(0编辑  收藏  举报