Automatically reconnecting QTcpSocket Client

I am trying to write a piece of code that periodically tries to connect to the server using QTcpSocket until the server is up and ready. The client should also automatically and periodically try to reconnect when the server is up until it is turned on again or the user closes the program manually.

What I did was subscribe to the connected and erroneous QTcpSocket signals. When I catch the error signal, I basically call the connectToHost method again.

My code periodically tries to connect to the host until the server is ready (this part works fine). However, the problem is that the server is down, it can never reconnect. When the connection does not work, I get RemoteHostClosedError as expected. But, again calling the connectToHost method inside the same method (where I catch RemoteHostClosedError), I got nothing. Even the error signal is not emitted by the QTcpSocket object.

I gave my code below.

TcpServerConnector::TcpServerConnector( SocketSettings socketSettings, QObject* parent) : QObject(parent), socket(new QTcpSocket()) { this->connect(this->socket, SIGNAL(connected()), this, SLOT(connectionSuccess_Handler()), Qt::DirectConnection); this->connect(this->socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectionError_Handler(QAbstractSocket::SocketError)), Qt::DirectConnection); } void TcpServerConnector::connectionError_Handler( QAbstractSocket::SocketError error ) { switch (error) { case QAbstractSocket::AddressInUseError: this->logger.log(LogLevel::ERR, "SOCKET ERROR: Address is already in use"); break; case QAbstractSocket::ConnectionRefusedError: this->logger.log(LogLevel::ERR, "SOCKET ERROR: Connection refused"); break; case QAbstractSocket::HostNotFoundError: this->logger.log(LogLevel::ERR, "SOCKET ERROR: Host not found"); break; case QAbstractSocket::RemoteHostClosedError: this->logger.log(LogLevel::ERR, "SOCKET ERROR: Remote host closed"); break; } this->socket->abort(); this->socket->close(); this->logger.log(LogLevel::DEBUG, "Reconnecting..."); SystemUtil::sleepCurrentThread(1000); this->socket->connectToHost(ip_address, port); } 

}

I check the status of QTcpSocket before and after calling the connectToHost method (the last line I quoted here). Before calling connectToHost, the state of UnconnectedState and after calling connectToHost, its state becomes Connection. Nothing unexpected. However, neither it can connect to the server nor emit an error signal.

Any idea?

Note. The connectToHost QTcpSocket method is called internally for the first time.

+4
source share
2 answers

For those who may encounter a similar situation, the reset method of QTcpSocket solved the problem.

+4
source

I was in this situation, this solution:

  connect(&tcpClient, SIGNAL(disconnected()), SLOT(ReconnectToHost())); void ReconnectToHost(){tcpClient.connectToHost(theServerAddress, port);} 
0
source

All Articles