【发布时间】:2015-07-30 09:30:48
【问题描述】:
我第一次尝试使用 Qt 创建多线程服务器。通常人们会使用QTcpServer::nextPendingConnection()返回的套接字指针和已经烘焙的套接字句柄——但是由于我在一个单独的线程上与连接客户端进行交互,我需要使用来自QTcpServer的qintptr handle单独创建套接字::incomingConnection(qintptr 句柄)。经过一个非常沉闷、充满错误的调试会话后,我设法将问题追查到 QTcpServer::incomingConnection() 从未被解雇?
有没有人遇到过类似的问题 - Qt 的最新版本有什么变化?
这些是我尝试过的:
QTcpServer::incomingConnection(qintptr handle)QTcpServer::incomingConnection(qintptr socketDescriptor)QTcpServer::incomingConnection(int handle)
编辑:
创建服务器实例:
TestServer *myServer = new TestServer();
myServer->initializeServer(1234);
调用者:
void TestServer::initializeServer(quint16 port)
{
mainServer = new QTcpServer(this);
mainServer->listen(QHostAddress::Any, port);
qDebug() << "Listening for connections on port: " << port;
}
服务器现在正在监听。当客户端连接时,应该调用incomingConnection(qintptr handle):
void TestServer::incomingConnection(qintptr socketDescriptor){
TestClient *client = new TestClient(this);
client->setSocket(socketDescriptor);
}
调用者:
void TestClient::setSocket(quint16 socketDescr)
{
socket = new QTcpSocket(this);
socket->setSocketDescriptor(socketDescr);
connect(socket, SIGNAL(connected()),this,SLOT(connected()));
connect(socket, SIGNAL(disconnected()),this,SLOT(disconnected()));
connect(socket, SIGNAL(readyRead()),this,SLOT(readyRead()));
}
在 connect() 信号上调用:
void TestClient::connected()
{
qDebug() << "Client connected..."; // This debug never appears in the console, since QTcpServer::incomingConnection isn't being fired.
}
【问题讨论】:
-
请附上一些你遇到错误的代码
-
您是否继承了 QTcpServer 以重新实现
QTcpServer::incomingConnection()?有关示例,请参见 Threaded Fortune 服务器:doc.qt.io/qt-5/qtnetwork-threadedfortuneserver-example.html -
是的,我已经对它进行了子类化并重新实现了它——我没有像财富服务器示例中那样添加 Q_DECLARE_OVERRIDE 宏。我会试一试并报告。
-
~~我没有像 Fortune server-example 那样添加 Q_DECLARE_OVERRIDE 宏。我会试一试并报告。 ~~ - 即使使用 Q_DECL_OVERRIDE 仍然无法正常工作。