将异步 QLocalServer 与 QEventLoop 一起使用
Using async QLocalServer with QEventLoop
我想在一个使用异步 signals/slots 而不使用 QCoreApplication
的应用程序中 运行 QLocalServer
。据我了解,这应该可以使用 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();
}
此致,
我成功了:
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();
}
我想在一个使用异步 signals/slots 而不使用 QCoreApplication
的应用程序中 运行 QLocalServer
。据我了解,这应该可以使用 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();
}
此致,
我成功了:
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();
}