Problem with recieving Data from QUdpsocket
-
Hello guys. I have a problem with recieving Data from my QUdpsocket. I can connect to my socket and write a Datagram but when it comes to recieving it, it doesnt work. Im pretty sure that my connect is also working but im not sure. Can someone please help me further? This is how my myudp.h looks like:
#ifndef MYUDP_H #define MYUDP_H #include <QObject> #include <QUdpSocket> class MyUDP : public QObject { Q_OBJECT public: explicit MyUDP(QObject *parent = nullptr); void sendMessage(std::string test); signals: public slots: void Read(); private: QUdpSocket *socket; }; #endif // MYUDP_H
And this is how my myudp.cpp looks like:
#include "myudp.h" #include <QDebug> MyUDP::MyUDP(QObject *parent) : QObject{parent} { socket = new QUdpSocket(this); socket->bind(QHostAddress::LocalHost, 7755); connect(socket, &QUdpSocket::readyRead, this, &MyUDP::Read); } void MyUDP::sendMessage(std::string test) { QByteArray Data; Data.append("testing 123"); socket->writeDatagram(Data, QHostAddress::LocalHost, 7755); } void MyUDP::Read() { qDebug() << "hello?"; QByteArray Recieved; Recieved.resize(socket->pendingDatagramSize()); //damit keine infos verloren gehen, wenn daten zu lang sind QHostAddress sender; quint16 senderPort; //16bit lange ports socket->readDatagram(Recieved.data(), Recieved.size(), &sender, &senderPort); //readDatagramm befüllt sozusagen das recieved qDebug() << "message from: " << sender.toString(); qDebug() << "message port: " << senderPort; qDebug() << "message: " << Recieved; }
And this is the part of the code of widget.cpp where the sendMessage function is being called:
void Widget::on_sendButton_clicked() { MyUDP server; MyUDP client; std::string test = ui->message_input->text().toStdString(); server.sendMessage(test); }
Does anyone have an idea why its not working? Thanks for the help!!!
-
@Metshiix Hi.There is a big mistake here.
When using bind function, your udpsocket becomes automatically the server(receiver).
so in your case, you have created two servers which is wrong.What to do is:For the server side(receiver or listener)
create a udp socket, bind it to Broadcast address, and a specified port
listen to received dataFor the client side(sender)
Create a udp socket
send the data using writeDatagram( data, address, port);
Hope it helps.