0
votes

I have to receive data from TCP socket. It has fixed 16-bytes header (one header's field is data length) and data. I receive it with BigEndian, but it was send with LittleEndian.

I can' find good solution for such a data reception. What is working for me now is (reading one of the header fields):

QByteArray packetType = tcpSocket->read(2);
QDataStream in(packetType);
in.setByteOrder(QDataStream::LittleEndian);
quint16 pT = 0;
in >> pT;

Is there any better way to set QByteArray endianess? Or a way to read specified number of bytes with QDataStream?

1
What don't you like about the code you have written?Dale Wilson
Fix the source! It should not have been sent as little endian in the first place.Arunmu
@DaleWilson I believe there is "less lines" solution.bLAZ
@Arunmu I can't. The source is Delphi 7 software which I can't edit.bLAZ

1 Answers

1
votes

You're almost doing it right. The intermediate QByteArray is unnecessary. You can set the data stream directly on the socket:

QTcpSocket socket;
QDataStream in(&socket);
in.setByteOrder(QDataStream::LittleEndian);
...
void onReadyRead() {
  in.startTransaction();
  uint16_t packet_type;
  in >> packet_type;
  if (in.status == QDataStream::Ok) {
    if (packet_type == Foo) {
      uint32_t foo_data;
      in >> foo_data;
      if (! in.commitTransaction())
        return; // not enough data
      // got a full packet here
    }
  }
  in.abortTransaction();
}