Solved Threading with QNetwork Problem (UDPSocket)
-
Hi Guys :)
I need some Help with a problem i have right now ...
Currently i'm sendig data from a raspberry Pi to a Port where i am trying to recieve this data qith a qt GUI ..
Also Because the recieving is not the only task of the GUI i created a Thread..My Problem is that i am recieving the First Value... and it's also the right value but then i get the message
QNativeSocketEngine::readDatagram() was called not in QAbstractSocket::BoundState or QAbstractSocket::ConnectedState
and no Values anymore ...
I Created the Thread via signal and Slotmain:
int main(int argc, char *argv[]) { QApplication a(argc, argv); QThread cThread; recievesesnsordata cObject; cObject.DoSetup(cThread); cObject.moveToThread(&cThread); cThread.start(); MainWindow w; w.show(); return a.exec(); }
recieve Header File:
#ifndef RECIEVESESNSORDATA_H #define RECIEVESESNSORDATA_H #include <QObject> #include <QDebug> #include <QThread> class QUdpSocket; class recievesesnsordata : public QObject { Q_OBJECT public: explicit recievesesnsordata(QObject *parent = nullptr); void DoSetup(QThread &cThread); public slots: void DoWork(); private: QUdpSocket *udpSocket2; }; #endif // RECIEVESESNSORDATA_H
recieve.cpp
#include "recievesesnsordata.h" #include <QtNetwork> recievesesnsordata::recievesesnsordata(QObject *parent) : QObject(parent) { } void recievesesnsordata::DoSetup(QThread &cThread) { connect(&cThread, SIGNAL(started()),this,SLOT(DoWork())); } void recievesesnsordata::DoWork() { while(true) { udpSocket2 = new QUdpSocket; udpSocket2->bind(45455,QUdpSocket::ShareAddress); QByteArray datagram; datagram.resize(udpSocket2->pendingDatagramSize()); udpSocket2->readDatagram(datagram.data(), datagram.size()); QList<QByteArray> test; test.push_back(datagram.data()); } } }
Thanks for your help in advance i really appreciate it !
-
You should not set up an infinite loop but rather connect to
QUdpSocket::readyRead
Also, you are creating 1 new socket every iteration (and leaking it)
-
the problem is i want that the thread is running in the background and recieve all the time data ... that's why i am using a infinite loop... i tried to create a new socket outside of the infinite loop but the problem is that i'm getting an exception because of the memory ... do you have an idea how i could realize this ?
-