c++qtsocketsqtnetworkqudpsocket

Receive data from specific address using QUdpSocket


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?


Solution

  • 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: