How to send QMap over socket?
-
to send as QByteArray
QByteArray atpCommandCentre::messageToQByteArray(const QMap<QString, int> data) { qDebug() <<this << "messageToQByteArray" << data; QByteArray ar; QDataStream out(&ar,QIODevice::WriteOnly); //Serializing out << data; // write the data return ar; }
On Server or where you have to read it back to QMap
QMap<QString, int> atpCommandCentre::messageFromQByteArray(QByteArray data) { qDebug() <<this << "messageFromQByteArray" << data; QMap<QString, int> myTmpMessage; QDataStream in(&data, QIODevice::ReadOnly); //Deserializing in >> myTmpMessage; return myTmpMessage; }
Hope that help you
-
Anyway, I do think that this post can be safely marked as Solved now, in order for others to know that it has been solved.
-
@arsinte_andrei when I qDebug "out" variable, it says: QVariant(Invalid)... is that ok? I have some problems receiving the data, so I'm trying to find out whats wrong step by step.
-
@YouKnowMe said in How to send QMap over socket?:
when I qDebug "out" variable, it says: QVariant(Invalid)
What is
out
?if the one socket sends:
QDataStream stream(socket); stream << map;
the receiving end should be something like:
// slot connected to QTcpSocket::readyRead QDataStream socketStream(socket); QMap<QString, int> data; for (;;) { socketStream.startTransaction(); socketStream >> data; if (socketStream.commitTransaction()) qDebug() << "Received " << data; else break; }
See
ChatClient::onReadyRead
of this example for an explanation of what that code is doing -
@YouKnowMe
so... first of all, how do you use my functions??
it should be something like that
pseudo codeQMap<QString, int> myMap myMap.insert("one", 1); myMap.insert("two", 2); myMap.insert("three", 3); QByteArray myMessageToSend = messageToQBuyteArray(myMap); qDebug() << myMessageToSend; // this has to work - this is the bytes that you are sending
anyway, if what you try is not working please post a bit of code to understand better what are you trying to do