Question

Recently I programmed to do file transmission with Qt. Thought it worked now, I'm still curious about what happened. Please help me find out the reason. Many thanks.

Why the size of head is bigger than the sum of sizeof(qin32), sizeof(qint32) and length of file name?(I guess it is the reason of function - setVersion())

QFileInfo info(file_to_send.fileName());
QByteArray head;
QDataStream out(&head, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_0);
out << qint32(file_to_send.size() + info.fileName().length() + sizeof(qint32)*2)
    << qint32(info.fileName().length())
    << info.fileName();
tcpClient.write(head);
Was it helpful?

Solution

You have made it to complicated. Pattern is like that:

QFileInfo info(file_to_send.fileName());
QByteArray head;
QDataStream out(&head, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_0);
out << qint32(0)
    << info.fileName(); // << YouCanAddMoreStuffHere;

out.device()->seek(0);
out << qint32(out.length());

tcpClient.write(head);

and read code:

void SomeClass::slotReadClient() { // slot connected to readyRead signal of QTcpSocket
    QTcpSocket *tcpSocket = (QTcpSocket*)sender();
    QDataStream clientReadStream(tcpSocket);

    while(true) {
        if (!next_block_size) {
            if (tcpSocket->bytesAvailable() < sizeof(qint32)) { // are size data available
                break;
            }
            clientReadStream >> next_block_size;
        }

        if (tcpSocket->bytesAvailable() < next_block_size) {
            break;
        }
        QString fileName;
        clientReadStream >> fileName; // >> YouCanAddMoreStuffHere; // same as above

        next_block_size = 0;
    }
}

OTHER TIPS

info.filename() writes out its own length

if you don't want that then you can do

QFileInfo info(file_to_send.fileName());
QByteArray head;
QDataStream out(&head, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_0);
QByteArray filename = info.fileName().toLatin1();
out << qint32(file_to_send.size() + filename .length() + sizeof(qint32)*2);
    << qint32(filename .length())
out.writeRawData(fileName.constData(), filename.length());
tcpClient.write(head);

using writeRawData which bypasses any built in encoding

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top