[Qt-interest] QTcpSocket suddenly disconnects

Thiago Macieira thiago.macieira at trolltech.com
Wed Aug 5 09:35:16 CEST 2009


Joshua Senecal wrote:
>Okay, I've traced through the code somewhat and here's what I've come up
>with thus far.
>
>If I terminate the server while the client is connected, the client
>immediately enters QAbstractSocketPrivate::readFromSocket() (why?).

Because when you get that FIN or RST packet, the TCP/IP stack in your 
operating system closes the client socket. It indicates that closing by 
telling the application that the socket is readable.

A zero-byte read from the socket is an EOF.

>Nothing is read obviously, but toward the end of the procedure is this
>block of code, the body of which is taken:
>
>if (!socketEngine->isValid()) {
>    socketError = socketEngine->error();
>    q->setErrorString(socketEngine->errorString());
>    emit q->error(socketError);
>#if defined(QABSTRACTSOCKET_DEBUG)
>    qDebug("QAbstractSocketPrivate::readFromSocket() read failed: %s",
>           q->errorString().toLatin1().constData());
>#endif
>    resetSocketLayer();
>    return false;
>}
>
>When execution reaches this line:
>
>emit q->error(socketError);

socketError is probably RemoteHostClosedError.

>execution immediately goes to a switch statement in my class'
>moc-generated code that handles signals. My socket which initiates a
>reconnect is called. The reconnect completes, but then code execution
>returns from the call to emit q->error(socketError) and continues. The
>next line is resetSocketLayer(). When this line executes, the server
>socket sees a disconnection from the client side. The client likewise
>disconnects.
>
>So, I think what's happening in a nutshell is the code that executes as
>a result of the original server disconnection is not given a chance to
>execute completely before my reconnect routines begin execution. I'll
>have to see what I can do to remedy this.

Good debugging! Your analysis seems flawless.

You may want to connect to the disconnected() signal, because it is 
emitted at a later point.

Another solution is to schedule a connect at the next event loop run, or 
after a timeout.

Note that if a TCP server is closed while there are open sockets, the 
operating system usually keeps the port unavailable for a given timeout. 
That means you will be unable to reconnect to the server until that 
timeout has passed, since the server won't be up yet.

-- 
Thiago Macieira - thiago.macieira (AT) nokia.com
  Senior Product Manager - Nokia, Qt Software
      Sandakerveien 116, NO-0402 Oslo, Norway
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090805/f60de91f/attachment.bin 


More information about the Qt-interest-old mailing list