简体   繁体   中英

Reading from TCP socket

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?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM