zoukankan      html  css  js  c++  java
  • 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;
  • 相关阅读:
    【Python3爬虫】一次应对JS反调试的记录
    【Python3爬虫】突破反爬之应对前端反调试手段
    学习CSS之如何改变CSS伪元素的样式
    学习CSS之用CSS实现时钟效果
    学习CSS之用CSS绘制一些基本图形
    【Python3爬虫】一次破解JS加密数据的记录
    Linux安装部署Redis(超级详细)
    Linux部署MongoDB
    使用Nginx对.NetCore站点进行反向代理
    Linux部署.NetCore站点 使用Supervisor进行托管部署
  • 原文地址:https://www.cnblogs.com/ph829/p/6145680.html
Copyright © 2011-2022 走看看