Reputation: 10621
Trying to read all the data transferred before disconnected :
while( socket->state() == QTcpSocket::ConnectedState )
if ( socket->bytesAvailable() > 0 )
qDebug("Read from client: %s", QString(socket->readAll()).toStdString().c_str());
But when I disconnected from the other end, it seems the socket->stated()
still stays QTcpSocket::ConnectedState
, how can I detect the socket is disconnected from the other end?
PS:
Do I have to use signal/slot mechanism ? Is it possible to avoid signal/slot mechanism ?
Upvotes: 2
Views: 586
Reputation: 7777
A while
loop of this sort completely prevents Qt's event loop from performing any processing, which isn't recommended. You can manually make calls to QCoreApplication::processEvents()
within the while
loop, which will likely allow your socket's state to progress, but this has side effects that you may not be expecting (like your application handling other events that may be associated with event handlers and signals on other classes).
It's recommended that you create a slot to handle data read from the socket (connected to the socket's readyRead()
signal) and another slot to handle changes in the socket's state (connected to the socket's stateChanged()
signal).
Upvotes: 4