简体   繁体   English

从QByteArray访问UDP数据报

[英]Access UDP Datagram from a QByteArray

I'm not sure I understand how the QByteArray Object works as of yet (it's raw char data, right?), but here's my dilemma: 我不确定我是否了解QByteArray对象的工作原理(它是原始char数据,对吗?),但这是我的两难选择:

I'm trying to access data from a UDP datagram in a function. 我正在尝试从函数中的UDP数据报访问数据。 Code: 码:

QByteArray buffer;  
buffer.resize(udpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
udpSocket->readDatagram(buffer.data(), buffer.size(), &sender, &senderPort);

This frees up the buffer for other incoming data and allows me to process my current datagram. 这样可以释放其他输入数据的缓冲区,并允许我处理当前的数据报。

As far as I can tell, I must store the data in a QByteArray, because any other attempt has made the compiler very cross with me. 据我所知,我必须将数据存储在QByteArray中,因为任何其他尝试都使编译器与我非常交叉。 Regardless, the data stored in the QByteArray is a series of unsigned 16 bit values(commands) that I need to access. 无论如何,存储在QByteArray中的数据是我需要访问的一系列无符号16位值(命令)。 Can it be read directly out of the QByteArray, and if so, how? 可以直接从QByteArray中读取它吗? I've had no luck doing so. 我没有运气。 If not, what's the best way to convert the entire array to quint16 array so that I can process the incoming data? 如果不是,将整个数组转换为quint16数组以便处理传入数据的最佳方法是什么? Thanks All!! 谢谢大家!

Once you have read the data with readDatagram, you need to access it in quint16 values. 使用readDatagram读取数据后,需要以quint16值访问它。

Two possible methods: 两种可能的方法:

  1. Use a quint16 buffer and store directly into it: 使用quint16缓冲区并直接存储在其中:

     //Set 1024 to any large enough size QVector<quint16> buffer(1024); qint64 readBytes = udpSocket->readDatagram((char*)buffer.data(), buffer.size()*sizeof(qint16), &sender, &senderPort); buffer.resize(readBytes/sizeof(quint16)); //Now buffer contains the read values, nothing more. 
  2. Use a QByteArray and "unserialize" it to quint16 values. 使用QByteArray并将其“反序列化”为quint16值。 This approach is more complex but is cleaner, since you have options for interpreting data format, such as endianness. 由于您可以选择解释数据格式(例如字节序)的方法,因此此方法更复杂,但更干净。

     //Set 2048 to any large enough size QByteArray buffer(2048); qint64 readBytes = udpSocket->readDatagram(buffer.data(), buffer.size(), &sender, &senderPort); buffer.resize(readBytes); QDataStream dataStream(&buffer, QIODevice::ReadOnly); //Configure QDataStream here, for instance: //dataStream.setByteOrder(QDataStream::LittleEndian); while(!dataStream.atEnd()) { quint16 readValue; dataStream >> readValue; //do something with readValue here } 

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

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