qtqtcpsocketqiodeviceqdatastream

Qt QTcpSocket streaming


My application sent object to the server via QTcpSocket.

Client:

void client::sendFile(QString path)
{
    QFile toSend(path);
    QByteArray rawFile;
    rawFile = toSend.readAll();

    QDataStream out(cl);
    out >> rawFile;
}

Server:

void server::handleClient()
{
    QTcpSocket *curCl = srv->nextPendingConnection();
    QByteArray z;
    QDataStream in(curCl);
    in >> z;

    QFile qwe("test.dat");
    qwe.write(z);
    qwe.close();
}

The problem is that nothing happens, but debug console told me:

QIODevice::write: device not open
QIODevice::read: device not open

... but the QDataStream object doesn't allow me to set open mode up! :( Whats wrong?


Solution

  • QFile + QFile.write (or QFile.read) requires QFile.open, see example:

    Write:

    QFile qwe("test.dat");
    if(qwe.open(QIODevice::WriteOnly | QIODevice::Text)) {
      qwe.write(z);
      qwe.close();
    } else {
      qDebug() << "Error";
    }
    

    or

    #include <QTextStream>
    
    ...
    
    QFile qwe("test.dat");
    if(qwe.open(QIODevice::WriteOnly | QIODevice::Text)){
       QTextStream out(&qwe);
       out << "This file is generated by Qt\n";
       qwe.close();
    } else {
      qDebug() << "Error";
    }
    

    Read:

    QFile toSend(path);
    if(toSend.open(QIODevice::ReadOnly | QIODevice::Text)) {//Open "read file"
        QByteArray rawFile;
        rawFile = toSend.readAll();
    
        QDataStream out(cl);
        out >> rawFile;
        toSend.close();//close
    }