How do I send and receive UDP packets in QT

2019-04-22 09:56发布

I am writing a small application in QT that sends a UDP packet broadcast over the local network and waits for a UDP responce packet from one or more devices over the network.

Creating the sockets and sending the broadcast packet.

udpSocketSend = new QUdpSocket(this);
udpSocketGet  = new QUdpSocket(this);
bcast = new QHostAddress("192.168.1.255");

udpSocketSend->connectToHost(*bcast,65001,QIODevice::ReadWrite);
udpSocketGet->bind(udpSocketSend->localPort());
connect(udpSocketGet,SIGNAL(readyRead()),this,SLOT(readPendingDatagrams()));

QByteArray *datagram = makeNewDatagram(); // data from external function
udpSocketSend->write(*datagram);

The application sends the packet properly and the response packet arrives but the readPendingDatagrams() function is never called. I have verified the packets are sent and received using Wireshark and that the application is listening on the port indicated in wireshark using Process Explorer.

2条回答
家丑人穷心不美
2楼-- · 2019-04-22 10:10

I solved the problem. Here is the solution.

udpSocketSend = new QUdpSocket(this);
udpSocketGet  = new QUdpSocket(this);
host  = new QHostAddress("192.168.1.101");
bcast = new QHostAddress("192.168.1.255");

udpSocketSend->connectToHost(*bcast,65001);
udpSocketGet->bind(*host, udpSocketSend->localPort());
connect(udpSocketGet,SIGNAL(readyRead()),this,SLOT(readPendingDatagrams()));

QByteArray *datagram = makeNewDatagram(); // data from external function
udpSocketSend->write(*datagram);

The device on the network listens on port 65001 and responds to packets on the source port of the received packet. It is necessary to use connectToHost(...) in order to know what port to bind for the response packet.

It is also necessary to bind to the correct address and port to receive the packets. This was the problem.

查看更多
男人必须洒脱
3楼-- · 2019-04-22 10:24

You're binding your udpSocketSend in QIODevice::ReadWrite mode. So that's the object that's going to be receiving the datagrams.

Try one of:

  • binding the send socket in write only mode, and the receive one in receive only mode
  • using the same socket for both purposes (remove udpSocketGet entirely).

depending on your constraints.

查看更多
登录 后发表回答