1
votes

I want to detect how many bytes are available for reading:

while( socket->ConnectedState == QTcpSocket::ConnectedState ) {
    if(socket->bytesAvailable() > 0)
        qDebug("%d", test->bytesAvailable());
}

I'm sure the socket is connected, but it seems the return value of byteAvailable is always 0 no matter how many bytes I wrote from the other end.

But when I detect after disconnection:

if (! socket->waitForDisconnected(-1)) {
        qDebug("Failed to receive disconnect message from client");
    }
    else {
        qDebug("%d", socket->bytesAvailable());
        qDebug(socket->readAll());
        qDebug("Disconnected from client");
    }
}  

Information sent to debug window is reasonable: 8 ABCDEFGH.

What may cause this to happen ?

PS:
This also seems to be a dead loop as it keeps running even after I disconnect from the other end. Maybe cause by this reason: QTcpSocket state always connected, even unplugging ethernet wire

1
@thuga I'm using QRunnable than QThread, is there event loop in QRunnable ?CDT

1 Answers

0
votes

There is already signal readyRead () which notifies you when a socket has data to be read. Why are you using a while loop?

Also you can write the size of the buffer and then the actual buffer to the socket. Then while reading at the other end, first read the #of bytes and then the buffer with this:

qint64 QIODevice::read ( char * data, qint64 maxSize ).