Receive data from specific address using QUdpSocket

333 views Asked by At

I'm trying to do a client-to-client communication over UDP. I'm using QUdpSocket to do that.

The IP of my first client is 127.0.0.2 and the IP of the second client is 127.0.0.3.

In my first client, I want to send data, so I'm doing this:

socket = new QUdpSocket(this);
socket->bind(QHostAddress("127.0.0.2"), (quint16)actual_port);

...

Data = QByteArray::fromRawData((const char *)stockR.data, crypt_packet.size_struct); 
socket->writeDatagram(Data, QHostAddress("127.0.0.3"), (quint16)port_other);

In my second client, I have this:

socket = new QUdpSocket(this);
socket->bind(QHostAddress("127.0.0.3"), (quint16)port_second);
     
...

QByteArray buffer;
buffer.resize(socket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
socket->readDatagram(buffer.data(), buffer.size(), &sender, &senderPort);

But I can't receive my data from readDatagram(), and I don't know why.

I do every function on both sides, which means I read and write on both clients (it's to do a VoIP call).

Does anyone know what my mistake is?

1

There are 1 answers

0
Botje On BEST ANSWER

The readDatagram method is non-blocking: you can only usefully call it if hasPendingDatagrams() is true. This flag is in turn governed by running the Qt event loop.

You have two options:

  • Use socket->waitForReadyRead() to block your program for a set time (30s);
  • Or put the above code in a slot handler connected to the readyRead signal and let the event loop run naturally, keeping your application responsive to other inputs.