0
votes

I would like to set QTcpSocket::KeepAliveOption on the server side, so that the connection gets automatically disconnected when the network connection is lost for some time.

However, the documentation says:

On Windows Runtime, QAbstractSocket::KeepAliveOption must be set before the socket is connected.

On a client, you would just create the socket, set the option, then connect it.

On the server side, you do not create the sockets, they are created and returned buy QTcpServer::nextPendingConnection(). These are already connected.

So am I basically stuck, and is the only viable option to implement "heartbeats" myself?

EDIT

I have created a QTcpServer subclass as suggested by talamaki for setting the flag on incoming connection sockets:

class CustomTcpServer : public QTcpServer
{
    Q_OBJECT

public:
    CustomTcpServer(QObject * parent = 0) : QTcpServer(parent) { }

    void incomingConnection(qintptr socketDescriptor)
    {
        QTcpSocket *socket = new QTcpSocket(this);
        socket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
        socket->setSocketDescriptor(socketDescriptor);
        addPendingConnection(socket);
    }
};

Then, i have set

\HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\TCPIP\Parameters\KeepAliveTime

To a DWORD value of 30000 (thirty seconds)

And rebooted the system to be sure it is used by the system

But, I still get no disconnected signal after several minutes, after having unplugged the ethernet cable of the remote client.

How to make the KeepAlive feature work?

Thanks

3

3 Answers

0
votes

You should be able override QTcpServer::incomingConnection and create QTcpSocket yourself instead of letting the framework do it.

0
votes

On Windows, AFAIK there are three parameters that govern the timeout of a TCP connection. You have set the KeepAliveTime, which is the time until an idle connection will be starting to send keep-alive segments (the connection must be idle, no segments have been sent, no Acks received). Then there is the number of keep-alives that need to be unanswered to determine that it is dead, which is TcpMaxDataRetransmissions. Finally, the is the time between the keep-alive segments which is KeepAliveInterval. Check with Wireshark, if empty TCP segments are being sent (which are the Keep-Alives). Some versions of Windows might misbehave, too and ignore some of the settings.

0
votes

Usually Servers re-starts the Listenning after a elapsed time without traffic. After close en re-open , new connections will arrive.

ALSO Client and Server can specify a test protocol like PING - PONG message on interval of X seconds, minutes, etc

In server side, when missing pings after X seconds, maybe indicate to restart the server. Best regards!