Pong

June 25th 2014, QTcpSocket State

June 25th 2014 QTcpSockets QThreads and the Event Loop in Qt | | June 28th 2014 Installing a Test Server

QWhat’s wrong with the following code snippet?

QSslSocket *socket = new QSslSocket;
...
socket->write(data);
socket->disconnectFromHost();
delete socket;

Since sockets are a state machine, the socket does not disconnect immediately, when it is told to disconnect from the host. It rather goes into “AboutToClose” state. In that state, it tries to send all pending data, when it is dispatched form the event loop. If all data is sent, a disconnected() signal is issued.

Now, if we delete the socket right after telling it to disconnect, we force the socket to close before it can be dispatched. As a result all remaining data to be sent is thrown away.

The solution is “waitForDisconnected”:

QSslSocket *socket = new QSslSocket;
...
socket->write(data);
socket->disconnectFromHost();
if (socket->state() != UnconnectedState) socket->waitForDisconnected();
delete socket;

Q Can we use “flush” instead of “waitForDisconnected”?

No we can’t, because flush will send some of the remaining data, but it might not send all of it!

June 25th 2014 QTcpSockets QThreads and the Event Loop in Qt | | June 28th 2014 Installing a Test Server

Options: