Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Qt serialization example
#include <QtCore/QCoreApplication>
#include <qdatastream.h>
#include <qvector3d.h>
#include <qdebug.h>
#include <qtcpserver.h>
#include <qtcpsocket.h>
int main(int argc, char* argv[])
{
QCoreApplication a(argc, argv);
QByteArray packed_msg;
QDataStream serializer(&packed_msg, QIODevice::WriteOnly);
QList<QVector3D> points_3d_send;
points_3d_send << QVector3D(1, 1, 1);
points_3d_send << QVector3D(2, 2, 2);
points_3d_send << QVector3D(3, 3, 3);
serializer << points_3d_send;
// <= send packed_msg over network
QTcpSocket clientSocket;
QDataStream to_server_stream(&clientSocket);
clientSocket.connectToHost(QHostAddress::LocalHost, 1122);
to_server_stream << packed_msg;
qDebug() << "sent:\n" << points_3d_send;
// <= receive packed_msg over network
QTcpServer tcp_server;
QObject::connect(&tcp_server, &QTcpServer::newConnection, [&tcp_server]() {
QTcpSocket* clientSocket = tcp_server.nextPendingConnection();
QObject::connect(clientSocket, &QAbstractSocket::readyRead, [clientSocket]() {
QDataStream from_client_stream(clientSocket);
QByteArray packed_msg;
// check if QByteArray is complete
from_client_stream.startTransaction();
from_client_stream >> packed_msg; // try to read QByteArray
// if QByteArray is not completely received -> repeat when more data arrives
if (!from_client_stream.commitTransaction()) {
return; // wait till more data arives
}
// QByteArray received completely -> deserialize data
QDataStream deserializer(packed_msg);
QList<QVector3D> points_3d_receive;
deserializer >> points_3d_receive;
qDebug() << "\nreceived:\n" << points_3d_receive;
});
});
tcp_server.listen(QHostAddress::LocalHost, 1122);
return a.exec();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment