QUdpSocket not sending data when created in QThread
-
In a nutshell, how do you send data when a QUdpSocket is created in a QThread?
Heres my QThread class header:
@
#ifndef UDP_H
#define UDP_H#include "defines.h"
#include <QThread>
#include <QtNetwork>class UDP : public QThread
{
Q_OBJECTpublic:
explicit UDP(QObject *parent = 0);
void run();
void commandSend();QUdpSocket *udp_socket; QByteArray data; QString host; QString port;
signals:
void dataReceived(QByteArray);private slots:
void udpSocketReadyRead();};
#endif // UDP_H
@Heres my QThread class cpp:
@
#include "udp.h"UDP::UDP(QObject *parent) :
QThread(parent)
{
}/*
// main run loop
/
void UDP::run()
{
/ object connects */
udp_socket = new QUdpSocket();
udp_socket->moveToThread(this);
connect(udp_socket, SIGNAL(readyRead()), this, SLOT(udpSocketReadyRead()));/* start run loop */ exec();
}
/*
// send (private function)
/
void UDP::commandSend()
{
/ check if the socket is already bound */
if (udp_socket->state() != QUdpSocket::BoundState){
// bind the socket
if (!udp_socket->bind(43680)){
QMessageBox errMsg;
errMsg.setWindowTitle("Error");
errMsg.setText("Error binding socket");
errMsg.exec();
return;
}
}/* send the initiate packet */ if (udp_socket->writeDatagram(data, QHostAddress(host), port.toInt()) < 0){ QMessageBox errMsg; errMsg.setWindowTitle("UDP Error"); errMsg.setText("Error sending packet"); errMsg.exec(); }
}
/*
// udp socket ready read (private slot)
*/
void UDP::udpSocketReadyRead()
{}
@Heres how i initialize in my main gui thread:
@
c_thread->host = IP;
c_thread->port = PORT;
...
...
// fill data buffer goes here
...
...
emit commandSend();
@When I call the "commandSend", it does not send the packet... I have watched it on wire shark.
I know that QThread spawns its own threads to deal with the run loop, but I am having a brain cramp trying to figure out how to successfully get the data sent out the socket. Any ideas?
Thanks in advance.
Edit: I have changed a little bit of the code to "moveToThread" to direct the socket connections to the specific thread. Yet, i am still unable to send data...