I'm trying to develop a UDP datagram receiver to read packets from a UDP server that update information via UDP datagrams. I want to receive the datagrams and after update the data reading the payload. I followed the Qt Tutorial Example for developing a Multicast Receiver. I just copied the code, but, while the example receives and read the datagram, the same code in my application does not. It does not want to work. What I'm getting wrong?
here is the code of the class I deveoloped:
UDPDataReceiver.h
class UDPDataReceiver: public QObject
{
Q_OBJECT
public:
explicit UDPDataReceiver(QObject *parent = nullptr);
public slots:
void readPendingDatagrams();
private:
QUdpSocket m_socket;
QHostAddress groupAddress4;
};
UDPDataReceiver.cpp
UDPDataReceiver::UDPDataReceiver(QObject *parent) : QObject(parent),
groupAddress4(QStringLiteral("234.5.6.7"))
{
const QHostAddress &localhost = QHostAddress(QHostAddress::LocalHost);
// for (const QHostAddress &address: QNetworkInterface::allAddresses()) {
// if (address.protocol() == QAbstractSocket::IPv4Protocol && address != localhost)
// qDebug() << address.toString();
// }
bool bound = m_socket.bind(localhost, 2471, QUdpSocket::ShareAddress);
bool joined = m_socket.joinMulticastGroup(groupAddress4);
connect(&m_socket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
}
void UDPDataReceiver::readPendingDatagrams()
{
QByteArray datagram;
while (m_socket.hasPendingDatagrams()) {
datagram.resize(int(m_socket.pendingDatagramSize()));
m_socket.readDatagram(datagram.data(), datagram.size());
qDebug()<<datagram.constData()<<"Example implementation";
}
}
In the constructor of my MainWindow class I call the code that follow to create an instance of the receiver.
dataReceiver = new UDPDataReceiver(this);
Trying to run the Qt example of the multicast receiver (https://doc.qt.io/qt-5/qtnetwork-multicastreceiver-example.html) it reads well the datagrams. With the same code in my application, nothing had been read.
Thanks to whom will help me.
I'll try to help you with a couple of tips.
If You use Windows You need to switch off your firewall or add your application to it's list. Next step. You can try to switch your variable
QUdpSocket m_socketintoQUdpSocket *m_socket. And try yo use cycledo{}while()like this code:Maybe the condition is not met, but on the second cycle it will probably work!
Let's try the best, my friend!