Search code examples
qtqt-signalsqlocalsocketqlocalserver

Using async QLocalServer with QEventLoop


I want to run a QLocalServer in an application using asynchronous signals/slots which does not use QCoreApplication. As far as I understand this should work using a QEventLoop:

void MyThread::startSocketServer()
{
    m_server = new QLocalServer();
    m_server->listen("ExamplePipe");

    /*
    // This works:
    m_server->waitForNewConnection(-1);
    auto socket = m_server->nextPendingConnection();
    socket->write("Test"); */

    // This signal is never triggered
    connect(m_server, &QLocalServer::newConnection, this, [this]()
    {
        auto socket = m_server->nextPendingConnection();
        connect(socket, &QLocalSocket::readyRead, this, [this, socket]()
        {
            //socket->readAll();
            //usleep(1000);
            //socket->write("Test");
        });
    });
}

void MyThread::run()
{
    QEventLoop eventLoop;
    startSocketServer();
    eventLoop.exec();
}

The synchronous version works as expected. Is there a way to use the asynchronous way with QLocalServer?

EDIT: Here is a version with the basics:

void MyThread::run()
{
    QEventLoop eventLoop;
    m_server = new QLocalServer();
    m_server->listen("ExamplePipe");

    connect(m_server, &QLocalServer::newConnection, &eventLoop, []()
    {
        // not triggered
    });
    eventLoop.exec();
}

Regards,


Solution

  • I got it working:

    void MyThread::run()
    {
        int argc = 0;
        char *argv[] = {NULL};
        m_qtApplication = new QCoreApplication(argc, argv);
    
        m_server = new QLocalServer();
        m_server->listen("ExamplePipe");
    
        connect(m_server, &QLocalServer::newConnection, m_qtApplication, []()
        {
            // works
        });
    
        m_qtApplication->exec();
    }