Search code examples
c++qtqtcpserver

qt qtcpserver is only working when it is created in main function


I just wrote a simle qtcpserver, which is nearly this example: QT QTcpServer::incomingConnection(qintptr handle) not firing?

The server is basically working, but only when it is created within the main function.

working:

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    TestServer server;

    return a.exec();
}

not working (this code won't work anyway like this, its just to show you what I mean):

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    classA cA;

    return a.exec();
}

classA::classA(QObject *parent) :
    QThread(parent)
{
    TestServer server;
}

When I create a class A within the main function and within A I create the tcpserver, the incomingConnection() function is never executed, although the server itself is started. I can see this because I get the "Server start at port ..." message from A's constructor:

TestServer::TestServer(QObject *parent):
    QTcpServer(parent)
{
    if (this->listen(QHostAddress::Any, 2323)) {
        qDebug() << "Server start at port: " << this->serverPort();
    } else {
        qDebug() << "Start failure";
    }
}

That means, that my main function now holds class A and the qtcpserver function. The qtcpserver function again creates a new thread when a client connected. What I want to do is to have the messages, received by the thread, in my class A. That is why I want to create the qtcpserver within the class A.

Does anybody have a suggestion for this? How can I create the server within A?

Thanks!


Solution

  • You need to make the object server a member to the class classA, because now this object destroys immediately after creation (because now you create it in a local scope)