【发布时间】:2012-07-24 19:16:42
【问题描述】:
我对 QTcpServer 在线程和阻塞方面的幕后工作方式很感兴趣。 QTcpServer 有一个 listen() 立即返回的方法。如果侦听成功开始,服务器将发出信号newConnection()。当listen() 方法返回时,我对服务器如何监听(是否在主线程上)感兴趣。带有 QTcpServer 的控制台应用程序的通常示例是这样的:
//main.cpp
int main(int argc, char* argv[])
{
QCoreApplication app;
MyServer server;
app.exec();
}
//MyServer.cpp
MyServer::MyServer(QObject *parent) : QObject(parent)
{
this->server = new QTcpServer(this);
connect(server, SIGNAL(newConnection()), this, SLOT(on_newConnection()));
if (!server->listen(QHostAddress::Any, 1234))
//do something in case of error
}
void MyServer::on_newConnection()
{
QTcpSocket* socket = server->nextPendingConnection();
//do some communication...
}
QTcpServer 是否依赖于现有的 QCoreApplication(或者可能是 QRunLoop)并正在运行以接收网络事件。如果不调用QCoreApplication::exec(),它可以正常工作吗?
【问题讨论】:
标签: qt qtcpserver