c++qudpsocket

QUdpSocket broadcast not working to more than one client


I have an application that uses QUdpSocket to broadcast a heartbeat message:

mpsckUDP = new QUdpSocket(this);
mpsckUDP->bind(QHostAddress::Broadcast, clsMainWnd::mscuint16Port);
QObject::connect(mpsckUDP, SIGNAL(readyRead()), this, SLOT(onUDPdataRdh()));

mscuint16Port is:

const quint16 clsMainWnd::mscuint16Port(8081);

The code that sends a message:

const QByteArray carybytData(/*My message*/);
qint64 int64Written(mpsckUDP->writeDatagram(carybytData, QHostAddress::LocalHost, clsMainWnd::mscuint16Port));

int64Written is assigned 47 after each call to writeDatagram. In my client applications which run on the same system:

mpsckUDP = new QUdpSocket(this);
uint uintPort(8081);
mpsckUDP->bind(QHostAddress::LocalHost, uintPort);
QObject::connect(mpsckUDP, SIGNAL(readyRead()), this, SLOT(onUDPdataRdy()));

The slot:

void clsMainWnd::onUDPdataRdy() {
    QHostAddress objSender;
    QByteArray arybytData;
    quint16 uint16Port;
    arybytData.resize(mpsckUDP->pendingDatagramSize());
    mpsckUDP->readDatagram(arybytData.data(), arybytData.size(), &objSender, &uint16Port);
    ...
}

I launch two instances on the client application on the same system the issue is that only the first instance is receiving the UDP broadcast, the other isn't receiving anything...

The intention is to have many clients and a single broadcasting application.


Solution

  • Main application:

    mpsckUDP = new QUdpSocket(this);
    //Connection only required if you are going to receive data back on UDP
    QObject::connect(mpsckUDP, SIGNAL(readyRead()), this, SLOT(onUDPdataRdy()));
    

    Broadcast logic:

    qint64 int64Written(mpsckUDP->writeDatagram(carybytData, QHostAddress::Broadcast, clsMainWnd::mscuint16Port));
    

    In the client applications:

    mpsckUDP = new QUdpSocket(this);
    mpsckUDP->bind(uintPort, QUdpSocket::ShareAddress);
    QObject::connect(mpsckUDP, SIGNAL(readyRead()), this, SLOT(onUDPdataRdy()));
    

    Now all is good!