3ef9g
3ef9g

Reputation: 881

How to send data from server to client as QByteArray/QDataStream

In the fortuneserver sample of Qt, a QString is sent by the method sendFortune(). Therefore one QString is selected from the QStringList fortunes:

QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << (quint16)0;
out << fortunes.at(qrand() % fortunes.size());
out.device()->seek(0);
out << (quint16)(block.size() - sizeof(quint16));

QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
clientConnection->write(block);

Is it also possible to send another type of data, like files, images or multiple strings? Or is it just possible to send a single string?

My second question: What is the advantage of sending data as QByteArry and why do I have to define (quint16) by setting up the QDataStream?

Upvotes: 3

Views: 5624

Answers (2)

Boy
Boy

Reputation: 7497

To know if you have read all the data send by the other side of the socket, I use the commitTransaction() function from QDataStream:

Client::Client()
{
    ....
    connect(tcpSocket, &QIODevice::readyRead, this, &Client::readData);
    ....
}

void Client::readData()
{
    in.startTransaction();

    QString data;
    in >> data;

    if (!in.commitTransaction())
    {
        qDebug() << TAG << "incomplete: " << data;
        // readyRead will be called again when there is more data
        return;
    }

    // data is complete, do something with it
    ....

Upvotes: 0

Asalle
Asalle

Reputation: 1337

You don't send the data as QDataStream, QDataStream is a class that impersonates a stream, a way to transfer data, like wire. QByteArray represents a storage for your data. So, you can send data as QByteArray. You can try QTcpSocket's member function called "int write(QByteArray)", like in the example you provided. Just take the image, the file, any other data and convert it to QByteArray. Here is where you will need QDataStream. Bind the stream to bytearray like this.

QByteArray dat; QDataStream out(&dat, QIODevice::WriteOnly);

and use out to fill dat.

out << myImage << myImage2;

When you had finished filling the QByteArray, send it:

mySocket.write(dat);

don't forget to check the return value. Read the docs and you will succeed.

Upvotes: 3

Related Questions