how to reconnect with server
I am using QTcpsocket and QtcpServer to implement client server resp. my client program waits till server starts and connect it. I want to reconnect with the server , when server get down after connection, but above code gives strange behaviour, it creates a lot of instance of server, and my program got hang.Please give suggestion to fulfil my aim, and please explain what is the problem in following code, it is a slot,in client program, connect 开发者_StackOverflow社区with disconnected() signal.
void TcpClient::connectionClosedByServer()
{
ui->lStatus->setText(tr("Error: Connection closed by server"));
closeConnection();
while(tcpSocket->state()!=QAbstractSocket::ConnectedState)
{
tcpSocket->abort();
tcpSocket->connectToHost(QHostAddress::LocalHost,6015);
sleep(6);
}
}
Intead of sleep(6)
try to use tcpSocket->waitForConnected(6000)
, otherwise your connection requests will never timeout.
精彩评论