一个写操作可以参考:
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() < ) {
break;
}
char buffer[]
quint32 peekedSize;
tcpSocket->peek(buffer, );
peekedSize = qFromBigEndian<quint32>(buffer); // default endian in QDataStream
if (peekedSize==0xffffffffu) // null string
peekedSize = ;
peekedSize += ;
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-.
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, );
stream.writeRawData(hello, slen);
QVariantMap myMap, inMap;
QByteArray mapData; myMap.insert("Hello", );
myMap.insert("World", ); QDataStream outStream(&mapData, QIODevice::WriteOnly);
outStream << myMap;
qDebug() << myMap;
QDataStream inStream(&mapData, QIODevice::ReadOnly);
inStream >> inMap;
qDebug() << inMap;