0

我想QLocalServer在应用程序中使用不使用QCoreApplication. 据我了解,这应该使用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();
}

同步版本按预期工作。有没有办法使用异步方式QLocalServer

编辑:这是一个基本的版本:

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

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

问候,

4

1 回答 1

0

我让它工作:

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();
}
于 2020-04-28T05:40:49.983 回答