Qt QUdpSocket triggers readyRead() on sending data

258 Views Asked by At

I have written following simple program for UDP communication:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    udpSocket = new QUdpSocket(this);
    udpSocket->bind(QHostAddress::AnyIPv4, 4000);
    connect(udpSocket, SIGNAL(readyRead()), this, SLOT(readDataFromSocket()));

    udpSocket->writeDatagram("Test Data", QHostAddress("192.168.2.91"), 3000);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::readDataFromSocket()
{
    while (udpSocket->hasPendingDatagrams()) {
           udpSocket->receiveDatagram();
          qDebug()<<"UDP data received";
      }
}

Now the problem is that, when I run this program, readyRead() also fires on sending data. Few interesting findings:

  • I have tried sending data to different IPs on my network. For few IPs it doesn't trigger my readyRead() function. But for most of the IPs readyRead() does trigger.

  • Though udpSocket->hasPendingDatagrams() returns true, but it doesn't have any data.

  • I am running Qt 5.12.3 (MSVC 2017, 32 bit). When I run same program in Qt 5.3.2 (MSVC 2010, 32 bit), it works fine, my readyRead() never fires.

Anyone can help?

1

There are 1 best solutions below

0
Soheil Armin On

As per qint64 QUdpSocket::writeDatagram(const char *data, qint64 size, const QHostAddress &address, quint16 port) docs:

Warning: Calling this function on a connected UDP socket may result in an error and no packet being sent. If you are using a connected socket, use write() to send datagrams.