我正在尝试使用udpReceiver
我qUdpSocket
单独编写的类来接收一些数据包QThread
:
class udpThread : public QThread
{
private:
QObject * parent;
public:
udpThread(QObject * parent = 0)
{
this->parent = parent;
}
void run()
{
UdpReceiver * test = new UdpReceiver(parent);
}
};
class UdpReceiver : public QObject
{
Q_OBJECT
private:
QUdpSocket * S;
int port;
public:
UdpReceiver(QObject* parent = 0) : QObject(parent)
{
port = 9003;
initialize();
}
UdpReceiver(int p,QObject* parent = 0) : QObject(parent)
{
port = p;
initialize();
}
void initialize()
{
S = new QUdpSocket();
S->bind(port);
S->connect(S,SIGNAL(readyRead()),this,SLOT(readPendingDiagrams()));
qDebug() << "Waiting for UDP data from port " << port << " ... \n";
}
public slots:
void readPendingDiagrams()
{
while(S->waitForReadyRead())
{
QByteArray datagram;
datagram.resize(S->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
S->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);
qDebug() << datagram.size() << " bytes received .... \n";
qDebug() << " bytes received .... \n";
}
}
};
这是main()
方法:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// UdpReceiver * net = new UdpReceiver();
MainWindow w;
udpThread * ut = new udpThread();
ut->start();
w.show();
return a.exec();
}
现在,当我使用udpReceiver
该类来获取没有它的数据包时,QThread
它工作得很好,但是当我使用udpThread
该类时,它没有得到数据包,或者至少raedyread()
信号没有以某种方式激活。当我尝试在没有QThread
我的 GUI 以某种方式崩溃并且整个程序挂起的情况下获取数据包时,这就是我想使用QThread
. 如果您能帮我解决这个问题,我将不胜感激:) 问候,