我有一个QMap对象:
QMap<QString, int> map;
,我想通过TCP套接字发送它。我必须将其转换为JSON然后发送还是?
答案 0 :(得分:0)
尝试使用这种方法:
在服务器端,使用它发送地图:
// to send Map
qint64 SendMap(QMap<String, int> map){
QByteArray block;
QDataStream sendStream(&block, QIODevice::ReadWrite);
sendStream << quint64(0) // for size of data
<< map; // your map
sendStream.device()->seek(0); // return back to set data size
sendStream << (quint64)(block.size() - sizeof(quint64)); // set data size
return socket->write(block); // send data
}
在客户端,当您需要一张地图时,可使用它来读取地图:
// to receive Map
QMap<QString, int> ReceiveMap(QTcpSocket *socket){
QDataStream readStream(socket);
quint64 dataBlockSize = 0;
while(true) {
if (!dataBlockSize) {
if (socket->bytesAvailable() < sizeof(quint64)) { // waiting data size
break; // to be available
}
readStream >> dataBlockSize;
}
if (socket->bytesAvailable() < dataBlockSize) { // waiting full data
break;
}
QMap<QString, int> map;
readStream >> map;
return map;
}
}