QT QTcpServer in thread; how to close listening server on exit?

4.3k Views Asked by At

I have a thread subclass like this

class MyThread : public QThread
{
public:
    MyThread (void);
    ~MyThread (void);

    void run();

    void stop(); // close server and terminate thread

public slots:
    void slotCloseServer();

signals:
    void signalCloseServer();

private:
    QTcpServer* m_pServer;
};

and the run() and the overall class definition is outlined below

MyThread::MyThread()
{
    connect(this, SIGNAL(signalCloseServer()), this, SLOT(slotCloseServer()));
}

void MyThread::run()
{
    m_pServer = new QTcpServer();

    if(m_pServer->listen(QHostAddress(QHostAddress::LocalHost), 8888) == 0)
    {
        qCritical("Server listen failed.");
    }
    else
    {
        exec();
    }
}

void MyThread::stop()
{
    emit signalCloseServer();
    quit(); // terminate thread
}

void MyThread::slotCloseServer()
{
    if (m_pServer && m_pServer->isListening())
    {
        m_pServer->close();
    }
}

Now from the main thread, I want to call stop() so it would signal to the thread instance to close the server and terminate itself but it never gets to slotCloseServer() and the listening port does not get released.

Any thoughts as to how to release the server socket before the terminating the thread?

Thanks,

2

There are 2 best solutions below

0
On

Why not call slotCloseServer() from stop()?

void MyThread::stop()
{
    slotCloseServer(); // close server

    quit(); // terminate thread
}

void MyThread::slotCloseServer()
{
    if (m_pServer && m_pServer->isListening())
    {
        m_pServer->close();
    }
}
0
On

I think for the cases when something should be done when a created object is destroyed(in you case thread termination) better to state needed actions in destructor of class of that object:

MyThread ::~MyThread (void)
{
    m_pServer->close();
}