如何在 QT 中发送和接收 UDP 数据包 [英] How do I send and receive UDP packets in QT

查看:344
本文介绍了如何在 QT 中发送和接收 UDP 数据包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 QT 编写一个小应用程序,它通过本地网络发送 UDP 数据包广播,并等待来自网络上一个或多个设备的 UDP 响应数据包.

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);

应用程序正确发送数据包,响应数据包到达,但从未调用 readPendingDatagrams() 函数.我已经使用 Wireshark 验证了数据包是发送和接收的,并且应用程序正在使用 Process Explorer 侦听 Wireshark 中指示的端口.

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.

推荐答案

我解决了这个问题.这是解决方案.

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);

网络上的设备监听65001端口,并在接收到的数据包的源端口上响应数据包.必须使用 connectToHost(...) 才能知道响应数据包绑定哪个端口.

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.

这篇关于如何在 QT 中发送和接收 UDP 数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆