Solved QUdpSocket.readyread is not emitting when QCoreApplication not created from main thread.
-
Re: Why the main thread is needed for QCoreApplication?
I wrote this code to create QCoreApplication from different thread. It is ok for many situations except udp send and QUdpSocket.readyread not working. Is it a bug or known issue?
#include <QCoreApplication> #include <QNetworkDatagram> #include <QObject> #include <QUdpSocket> #include <thread> class UDPListener : public QObject { public: UDPListener(){} void startListening(quint16 port) { if (udpSocket.bind(port)) connect(&udpSocket, &QUdpSocket::readyRead, this, &UDPListener::processPendingDatagrams); } private: QUdpSocket udpSocket; public Q_SLOTS: void processPendingDatagrams() { while (udpSocket.state() == QUdpSocket::BoundState && udpSocket.hasPendingDatagrams()) { QNetworkDatagram datagram = udpSocket.receiveDatagram(); qDebug() << datagram.data(); } } }; void runsInOtherThread(int argc, char *argv[]) { QCoreApplication a(argc, argv); a.exec(); } void udpSend() { quint16 port = 5000; QHostAddress pTargetAddress; pTargetAddress.setAddress("127.0.0.1"); QUdpSocket test; test.writeDatagram("hello",5,pTargetAddress,port); } #define OTHERTHREAD int main(int argc, char *argv[]) { #ifdef OTHERTHREAD std::thread t(runsInOtherThread, argc, argv); #else QCoreApplication a(argc, argv); #endif UDPListener u; u.startListening(5000); udpSend(); std::thread t2(udpSend); #ifdef OTHERTHREAD t.join(); #else a.exec(); #endif return 0; }
-
@Diren
I don't know if this is relevant/the cause, but as we have said to another similar-ish post elsewhere: really think you should do thread work viaQThread
notstd::thread
if you want Qt things to work smoothly...? -
It shouldn't matter what thread the
QCoreApplication
is but you still have to run an event loop in the thread that owns theUDPListener
. The thread that should take care of executing theprocessPendingDatagrams
is blocked byt.join();
in your example -
@VRonin
When i move 2 lines to
UDPListener u;
u.startListening(5000);between
QCoreApplication a(argc, argv);
and
a.exec();it works. I have to think about it. Thank you.
-
@Diren said in QUdpSocket.readyread is not emitting when QCoreApplication not created from main thread.:
it works.
time to mark your post as solved then? thanks.