I have a QMap object:
QMap<QString, int> map;
and I would like to send it over TCP socket. Do I have to convert it to JSON and then send it or?
I have a QMap object:
QMap<QString, int> map;
and I would like to send it over TCP socket. Do I have to convert it to JSON and then send it or?
Try to use this approach:
On Server side use this to send a map:
// 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
}
On Client side, when you expect a map, use this to read a map:
// 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;
}
}