简体   繁体   English

从TCP套接字读取

[英]Reading from TCP socket

I have to receive data from TCP socket. 我必须从TCP套接字接收数据。 It has fixed 16-bytes header (one header's field is data length) and data. 它具有固定的16字节标头(一个标头的字段是数据长度)和数据。 I receive it with BigEndian, but it was send with LittleEndian. 我是通过BigEndian收到的,但是是通过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? 有没有更好的方法来设置QByteArray的字节序? Or a way to read specified number of bytes with QDataStream? 还是使用QDataStream读取指定数量的字节的方法?

You're almost doing it right. 您几乎做对了。 The intermediate QByteArray is unnecessary. 中间的QByteArray是不必要的。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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