1

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Adnan
  • 2,986
  • 7
  • 43
  • 63
  • 1
    Does the call to `QUdpSocket::bind` always succeed? What happens if you remove that call -- do you still receive the `readyRead` signal? – G.M. Nov 06 '19 at 10:44
  • Yes, QUdpSocket::bind always succeed. I removed the bind call, but still receive readyRead signal. – Adnan Nov 07 '19 at 04:16

1 Answers1

0

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.

Soheil Armin
  • 2,725
  • 1
  • 6
  • 18