0
votes

I'm writing client-server app, which uses QTcpSocket and QTcpServer. Here are the disconnected() slots:

server:

    void testServer::disconnected()
{
    socket = qobject_cast<QTcpSocket*>(sender());
    qDebug() << " - CLIENT DISCONNECTED";
    socket->disconnectFromHost();

    if(server->isListening())
    {
        server->close();
        qDebug() << " - SERVER CLOSED";
    }
}

client:

void testClient::disconnected()
{
    qDebug() << " - SERVER DISCONNECTED";
    tcpSocket->disconnectFromHost();
}

I face strange behavior when I try to imitate possible crashes when both sides are connected: when I close the server I can always reconnect to the new one with my client. But if I close the client while being connected, I can reconnect the server to the client just two times. And no more.

On the third "establish connection - restart the client - connect to the server" routine I always fail.

QTcpServer::newConnection()

signal is emitted, but

server->hasPendingConnections()

returns false, so I can't assign the socket with

socket = server->nextPendingConnection()

What's the problem with reconnecting QTcpServer? Also, server and client always runs on const ports, e.x. 1234 for server and 4321 for client. Can this be the issue?

1
What is maxPandingConnections on server? Why you are doing server->close() if you need a reconnect feature?Dmitry Sazonov

1 Answers

1
votes

server->close() ends the operation of the server. It won't accept any more connections, and any pending ones will be immediately closed as well. There's a race between the emission of the newConnection signal and the use of hasPendingConnections. The latter provides a correct answer - the server is closed at that point.

C.f. the documentation:

void QTcpServer::close()

Closes the server. The server will no longer listen for incoming connections.