Question

I'm trying to create a client that should connect to a C server. I must use TCP. I already have a server which is fully functional, but I'm unable to connect my client. I don't want to send any data to server (at this point). I just want to establish a connection and open up a new dialog box.

Here is the code in Void Login::on_pushButton_clicked() slot. // pushButon is my login button

pSocket = new QTcpSocket (this);
connect (pSocket, SIGNAL(readyRead()), SLOT(waitNextStep()));
pSocket->connectToHost(ui->lineEdit->text(), ui->lineEdit_2->text().toInt());
if(pSocket->waitForConnected())
{
    Menu mMenu;
    mMenu.setModal(true);
    mMenu.exec();
}
else
{
    QMessageBox::critical(this,tr("Error"),tr("Error at Connect"));
}

I already defined the Menu class and I know it's functional since I tested it without the connection part. The IP fetching part from the lineEdits is also functional. The pSocket is declared in the Login class, as a private member (QTcpSocket *pSocket;).

Unfortunatelly I'm new to QT and I don't really know what the 'waitNextStep()' function should containt. I just did a return 1; I am unsure about the SLOT in the connect function since I noticed in many examples that there were different functions there.

If I run the program I get no errors and the program executes just fine. But when I hit the login button, the dialog box freezes for ~15 seconds - it's unresponsive. After that, I get the 'Error at connect' message. Any help will be much appreciated.

Was it helpful?

Solution

Unfortunatelly I'm new to QT and I don't really know what the 'waitNextStep()' function should containt. I just did a return 1; I am unsure about the SLOT in the connect function since I noticed in many examples that there were different functions there.

It highly depends on your use case, but that is usually the handler of the incoming data whatever you wish to do with it, potentially including that you just store it in a member variable for the moment.

If I run the program I get no errors and the program executes just fine. But when I hit the login button, the dialog box freezes for ~15 seconds - it's unresponsive. After that, I get the 'Error at connect' message. Any help will be much appreciated.

It is because if(pSocket->waitForConnected()) is the blocking (i.e. sync) usage of the asynchronous Qt operation. What I would suggest to do instead is to connect to the connected signal as per documentation:

void QAbstractSocket::connected() [signal]

This signal is emitted after connectToHost() has been called and a connection has been successfully established.

Note: On some operating systems the connected() signal may be directly emitted from the connectToHost() call for connections to the localhost.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top