1
votes

I am making simple client server program using QTcpServer, QTcpSocket with out using thread,in fedora. I want to make my application, independent of sequence of what is running first, client or server.My application is running well when I start server first, but I am not getting any way to make client wait, while server is not start and connect with serve as server start. I used waitForConnection() but it is not helping. Please give some suggestions.

TcpClient::TcpClient(QWidget *parent) : QMainWindow(parent),
ui(new Ui::TcpClient) 

{
ui->setupUi(this);
tcpSocket= new QTcpSocket(this);
tcpSocket->connectToHost(QHostAddress::LocalHost,6178);     
connect(tcpSocket, SIGNAL(connected()), this, SLOT(sendRequest()));
connect(tcpSocket, SIGNAL(disconnected()),this, SLOT(connectionClosedByServer()));      
connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),this, SLOT(error())); 
.
.
..

}

void TcpClient::error() 

{ 
 ui->lStatus->setText(tcpSocket->errorString());
 closeConnection(); 
 tcpSocket->connectToHost(QHostAddress::LocalHost,6178);
 } 
2

2 Answers

2
votes

On the client, useconnectToHost(). Listen to hostFound() or connected() for success, and error() For failure. On failure, just try to connect again (maybe after 1 to 10 seconds, using QTimer::singleShot().)

This will allow the rest of your app to keep running while connection attempts are being made.

0
votes

Simple call of connectToHost from within a slot connected to error() doesn't work for me without Qt::QueuedConnection connection option. See post by Jonas Mauricio Gastal QTcpSocket reconnect after connection lost stay in ConnectingState. Sorry for my English.