QPacketProtocol Class

The QPacketProtocol class encapsulates communicating discrete packets across fragmented IO channels, such as TCP sockets. More...

Header: #include <QPacketProtocol>
Inherits: QObject

Public Functions

QPacketProtocol(QIODevice *dev, QObject *parent = nullptr)
qint64 packetsAvailable() const
QByteArray read()
bool waitForReadyRead(int msecs = 3000)

Detailed Description

\internal

QPacketProtocol makes it simple to send arbitrary sized data "packets" across fragmented transports such as TCP and UDP.

As transmission boundaries are not respected, sending packets over protocols like TCP frequently involves "stitching" them back together at the receiver. QPacketProtocol makes this easier by performing this task for you. Packet data sent using QPacketProtocol is prepended with a 4-byte size header allowing the receiving QPacketProtocol to buffer the packet internally until it has all been received. QPacketProtocol does not perform any sanity checking on the size or on the data, so this class should only be used in prototyping or trusted situations where DOS attacks are unlikely.

QPacketProtocol does not perform any communications itself. Instead it can operate on any QIODevice that supports the QIODevice::readyRead() signal. A logical "packet" is simply a QByteArray. The following example how to send data using QPacketProtocol.

 QTcpSocket socket;
 // ... connect socket ...

 QPacketProtocol protocol(&socket);

 // Send a packet
 QDataStream packet;
 packet << "Hello world" << 123;
 protocol.send(packet.data());

Likewise, the following shows how to read data from QPacketProtocol, assuming that the QPacketProtocol::readyRead() signal has been emitted.

 // ... QPacketProtocol::readyRead() is emitted ...

 int a;
 QByteArray b;

 // Receive packet
 QDataStream packet(protocol.read());
 p >> a >> b;

\ingroupio

Member Function Documentation

[explicit] QPacketProtocol::QPacketProtocol(QIODevice *dev, QObject *parent = nullptr)

Construct a QPacketProtocol instance that works on dev with the specified parent.

qint64 QPacketProtocol::packetsAvailable() const

Returns the number of received packets yet to be read.

QByteArray QPacketProtocol::read()

Return the next unread packet, or an empty QByteArray if no packets are available. This method does NOT block.

bool QPacketProtocol::waitForReadyRead(int msecs = 3000)

This function locks until a new packet is available for reading and the readyRead() signal has been emitted. The function will timeout after msecs milliseconds; the default timeout is 30000 milliseconds.

The function returns true if the readyRead() signal is emitted and there is new data available for reading; otherwise it returns false (if an error occurred or the operation timed out).