0

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,

Hyndrix
  • 4,282
  • 7
  • 41
  • 82
  • 1
    No idea about avoiding `QCoreApplication`, but looks like `MyThread` is sublassed from `QThread`. Why `eventLoop.exec()` but not just `exec()` ? – Vladimir Bershov Apr 27 '20 at 19:06
  • 1
    As I know, signal delivery requires event loop in the **receiver's thread**. Do you have such event loop, where **this** lives? – Vladimir Bershov Apr 27 '20 at 19:10
  • I have added a short plain example which also does not work. – Hyndrix Apr 28 '20 at 04:21
  • It would also be viable to create a ``QCoreApplication`` instance in the ``QThread`` (which I actually tried but it did not work). – Hyndrix Apr 28 '20 at 04:22

1 Answers1

0

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();
}
Hyndrix
  • 4,282
  • 7
  • 41
  • 82