0

I am confused on how should I receive and send structures over a QTcp Socket.

in.startTransaction();

QBytearray data;
in >> data;

if (!in.commitTransaction())
{
    qDebug()  << "incomplete: " << data;
    return;
}

so say my packet looks like this in bytes (01 00 00 68 65 6c 6c 6f )

build my struct then use qdatastream operators to deserialize or serialize the packet data....

what do i do about padding...

some exaxmples would be helpfull

Kian
  • 1,319
  • 1
  • 13
  • 23
Sunfluxgames
  • 71
  • 1
  • 4

1 Answers1

2

The layout of your struct in memory is compiler and architecture specific; do not try to make it exactly match the bytes in the networking packet, but instead explicitly translate between the structure in memory and the network packet, i.e. by defining appropriate streaming operators

QDataStream &operator<<(QDataStream &, const YourClass &)
QDataStream &operator>>(QDataStream &, YourClass &)

How these operators are implemented obviously depends on the data on the line and on YourClass, but to give you a simple example

struct S { int a , b };

QDataStream &operator<<(QDataStream &stream, const S &s) {
    stream << s.a << s.b;
    return stream;
}

QDataStream &operator<<(QDataStream &stream, S &s) {
    stream >> s.a >> s.b;
    return stream;
}

will serialize and de-serialize a custom struct S;

kkoehne
  • 1,176
  • 9
  • 17
  • what do i do about the null bytes in the network packet? some of them can be 100+bytes or more depending from the device card. what you posted is kind of what i did. so any call to Stream will auto send it to the socket i dont have to write it to the IO socket... – Sunfluxgames Jan 03 '18 at 17:32
  • So are you both reading and writing the packet, or only reading it? The exact layout in bytes on the network should be none of your concern if you both read and write via a QDataStream, 'which is 100% independent of the host computer's operating system, CPU or byte order.' (see http://doc.qt.io/qt-5/qdatastream.html#details). – kkoehne Jan 04 '18 at 16:20