QDataStream designed to provide platform-independent data serialization.
For example, you want to save some float to a file (or send it over the tcp stream) in some binary format. Then this float should be read from this file (or obtained from tcp) on another PC with a different processor and even with a different byte order (endianness).
So, QDataStream can be used for such a task. It allows you to encode basic C ++ data types and decode source values ββon any other platform.
If you just want to save binary data from a TCP stream, as well as a binary file, you do not need QDataStream . You can do this directly or synchronously, blocking the stream, or asynchronously using the readyRead () socket signal.
Example 1. Blocking socket for a stream without a GUI
QFile file("out.bin"); if (!file.open(QIODevice::WriteOnly)) return; char buffer[50]; forever { int numRead = socket.read(buffer, 50); // do whatever with array file.write(buffer, numRead); if (numRead == 0 && !socket.waitForReadyRead()) break; }
Example 2. Asynchronous non-blocking socket
// This slot is connected to QAbstractSocket::readyRead() void SocketClass::readyReadSlot() { while (!socket.atEnd()) { QByteArray data = socket.read(100); file.write(data); } }
These examples are based on the QAbstractSocket Class documentation (there you can find a detailed explanation of how this works).
source share