Hi there,
i would like to be always connected with a udp server... but my gui should never block!
Therefore i decided to move the udpsocket in a single thread... The thread reads data and parses the data and after that the thread emits signals... (signals not implemented yet!)
Also the thread should sometimes write some data to the socket... (not implemented yet)
My code works but i'm not sure if this code/design is correct.
Previously there was a little problem: I only received one datagram and i got the warning "QObject: Cannot create children for a parent that is in a different thread. "Code:#include "uthread.h" #include <iostream> UThread::UThread(QObject* parent) : QThread(parent) { } void UThread::run() { //Setup socket = new QUdpSocket(); socket->bind(QHostAddress::LocalHost, 2323); QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readData()), Qt::DirectConnection); exec(); } void UThread::readData() { while(socket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(socket->pendingDatagramSize()); QHostAddress sender; quint16 port; socket->readDatagram(datagram.data(), datagram.size(), &sender, &port); parse(datagram); } } void UThread::parse(QByteArray data) { QString q(data); std::cout << q.toStdString() << std::endl; }
I fixed it with this line (I added DirectConnection).
Is this the right way?Code:QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readData()), Qt::DirectConnection);
Thank you!

Reply With Quote

