我坚持使用关于线程 qt-networking 的教程(在这里:http ://doc.qt.io/qt-5/qtnetwork-threadedfortuneserver-example.html ),我做了一些小改动并将其集成到我的主程序中. 但是incomingConnection()
永远不会被执行,另一方面,客户端能够连接。由于我想使用incomingConnection()它已经过时了,SIGNAL(newConnection())
但即使这样也行不通。
有人知道出了什么问题吗?
这里我的.h
#include <QtNetwork>
#include <QTcpServer>
#include <QTcpSocket>
#include <QThread>
class WirelessNetThread: public Thread
{
Q_OBJECT
public:
WirelessNetThread(int socketDescriptor, QObject * parent);
void run() Q_DECL_OVERRIDE;
signals:
void error(QTcpSocket::SocketError socketError);
private:
int socketDescriptor;
QString text;
};
class WirelessNet : public QTcpServer
{
Q_OBJECT
public:
WirelessNet(QObject *parent = 0);
protected:
void incomingConnection(qintptr socketDescriptor) Q_DECL_OVERRIDE;
};
和.cpp
WirelessNetThread::WirelessNetThread(int socketDescriptor, QObject *parent):QThread(parent), socketDescriptor(socketDescriptor)
{
}
void WirelessNetThread::run()
{
QTcpSocket tcpSocket;
if ( !tcpSocket.setSocketDescriptor(socketDescriptor))
{
emit error(tcpSocket.error());
return;
}
tcpSocket.disconnectFromHost();
tcpSocket.waitForDisconnected();
}
WirelessNet::WirelessNet(QObject *parent): QTcpServer(0)
{
listen(QHostAddress::Any, 5220);
printf("is listening %d\n", this->isListening());
}
void WirelessNet::incomingConnection(qintptr socketDescriptor)
{
qDebug() << "incomming \n";
printf("incomming \n");
WirelessNetThread *thread = new WirelessNetThread(socketDescriptor, this);
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
这里是我的主程序的摘录,它是在哪里启动的(顺便说一句,如果我省略moveToThread()并不重要:
WirelessNet *wifi = new WirelessNet(this->parent());
wifi->moveToThread(this->thread());
如果我在wifi初始化后添加这些行,即使这也没有影响:
wifi = new WirelessNet(this->parent());
QEventLoop testLoop;
testLoop.exec();
换句话说,“incomming”永远不会被打印出来,所以我无法继续工作。有谁知道,这几乎是 1:1 的教程中的代码,这让我感到困惑。