Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Qdatastream read data from socket and write into file

I need to receive binary data(reading float) through a QTcpSocket and write them into Qfile using QDatastream. But I am having some problems with QDataStream. As follows, I can only achieve it using this way :

QDataStream in(socket);
in.setFloatingPointPrecision ( QDataStream::SinglePrecision);
float data;
in >> data;

QFile file("file.dat"); 
file.open(QIODevice::WriteOnly); 
QDataStream out(&file);
out << data;

I have to create two Qdatastream and write float into Qfile after reading it.I mean, can I read stream and write it into file directly by one Qdatastream in order to getting more efficient.

Am I having some blind spot about the usage of QDataStream?Anyone can help me to solved my problem?Many thanks.

like image 494
Chen Xu Avatar asked Aug 05 '15 03:08

Chen Xu


1 Answers

QDataStream is designed to provide platform independent data serialization.

For example, you want to save some float to a file (or to send it over tcp stream) in some binary format. Then this float should be read from that file (or received from tcp) on another PC with different CPU and even different byte order (endianness).

So, QDataStream can be used for such task. It allows you to encode C++ basic datatypes and to decode the original values on any other platform.

If you just want to save binary data from a TCP stream as is to a binary file then you do not need QDataStream. You can do it directly either synchronously blocking thread or asynchronously using readyRead() socket signal.

Example 1. Blocking socket for non-GUI thread

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

Those examples are based on the documentation of QAbstractSocket Class (there you can find detailed explanation how it works).

like image 66
Orest Hera Avatar answered Oct 13 '22 10:10

Orest Hera