Qt udp接收数据程序
时间: 2023-09-17 18:15:03 浏览: 55
以下是一个简单的 Qt UDP 接收数据程序示例:
```cpp
#include <QtNetwork/QUdpSocket>
#include <QDebug>
class UdpReceiver : public QObject
{
Q_OBJECT
public:
UdpReceiver(QObject *parent = nullptr)
: QObject(parent)
{
// 创建 UDP socket
m_udpSocket = new QUdpSocket(this);
// 绑定到本地端口号 1234
m_udpSocket->bind(1234);
// 当 UDP 数据包到达时,会触发 readyRead 信号
connect(m_udpSocket, &QUdpSocket::readyRead, this, &UdpReceiver::processPendingDatagrams);
}
private slots:
void processPendingDatagrams()
{
while (m_udpSocket->hasPendingDatagrams()) {
// 从 socket 中读取数据,并获取发送者的地址和端口号
QByteArray datagram;
QHostAddress senderAddress;
quint16 senderPort;
datagram.resize(m_udpSocket->pendingDatagramSize());
m_udpSocket->readDatagram(datagram.data(), datagram.size(), &senderAddress, &senderPort);
// 输出接收到的数据
qDebug() << "Received datagram:" << datagram << "from" << senderAddress.toString() << ":" << senderPort;
}
}
private:
QUdpSocket *m_udpSocket;
};
```
你可以在需要接收 UDP 数据的地方创建一个 `UdpReceiver` 对象即可。当有 UDP 数据包到达时,`processPendingDatagrams()` 槽函数会被调用,可以在该函数中处理接收到的数据。