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.