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;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM