Question

I have a server to which multiple clients can connect to. The client is GUI while the server is command line. The client has several functions (such as connect and login) which, when sent to the server should receive a reply.

Basically I need to run the QTcpSocket functions waitForConnection and waitForReadyRead. However, I need to do this without blocking the UI.

What I thought of doing was the following: Have a class (Client) implement QThread which does all the waiting. This is created in main.

Client::Client (...)
{
    moveToThread (this); // Not too sure what this does
    mClient = new QTcpSocket (this);
    start();
}

void Client::run (void)
{
    exec();
}

void Client::connectToServer (...)
{
    mClient->connectToHost (hostname, port);
    bool status = mClient->waitForConnected (TIMEOUT);

    emit connected (status);
}

void Client::login (...)
{
    ... Similar to connectToServer ...
}

Then the GUI (for example, ConnectToServerDialog) I run this whenever I am ready to make a connection. I connect the "connected signal" from the thread to the dialog so when I am connected or connection timed out it will emit this signal.

QMetaObject::invokeMethod (mClient, "connectToServer", Qt::QueuedConnection,
    Q_ARG (const QString &, hostname), Q_ARG (quint16, port));

I am getting an assert failure with this (Cannot send events to objects owned by a different thread.) Since I am fairly new to Qt I don't know if what I am doing is the correct thing.

Can somebody tell me if what I am doing is a good approach and if so why is my program crashing?

Was it helpful?

Solution

I don't recommend start thread in constructor.

Initialize it like:

Client * client = new Client();
client->moveToThread(client);
client->start();

Or if you don't want to use such solution, add in constructor before start(); line this->moveToThread(this);

upd: sorry, i didn't saw at first time, that you have this string.

OTHER TIPS

The best thing is never to call methods like waitForBlah() ... forcing the event loop to wait for an undetermined period introduces the possibility of the GUI freezing up during that time. Instead, connect your QTcpSocket's connected() signal to some slot that will update your GUI as appropriate, and let the event loop continue as usual. Do your on-connected stuff inside that slot.

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