Search code examples
qtqtnetworkqtcore

Empty buffer when reading from a QTcpSocket


I am creating a simple threaded TCP server (based on the threaded Fortune server example). I have connected the readyRead signal to my readCommand slot, and I confirmed that the readCommand function fires after I've telnetted to my server and sent a string (followed by enter).

The function below outputs "In readCommand" once I send the string HELLO, then the output "new inBuffer" always shows empty ("").

void FortuneThread::readCommand()
{
    qDebug() << "in readCommand" << endl;
    QDataStream in(tcpSocketPtr);
    in.setVersion(QDataStream::Qt_4_0);
    in >> inBuffer;
    qDebug() << "new inBuffer: " << inBuffer << endl;
    ...
}

If I print out tcpSocket->bytesAvailable(), then I see a growing count of characters as I send more via telnet. I'm just not getting them out of the socket...the code above is copied from the Fortune Client example so I assumed it would work. Am I using QDataStream wrong?


Solution

    • You should not initialize your QDataStream with QTcpSocket.

    • You should read the data from the socket io device with QByteArray QIODevice::readAll().

    • You should write the byte array of the previous operation into the data stream with the "<<" operator.

    So, the code should look something like this:

    void FortuneThread::readCommand()
    {
        QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out << tcpSocketPtr->readAll();
        ...
    }