qt实现udp接收和发送
时间: 2024-01-15 20:19:53 浏览: 362
以下是使用Qt实现UDP接收和发送的示例代码:
1. UDP接收:
```cpp
// 创建QUdpSocket对象
QUdpSocket udpSocket;
// 绑定端口号
udpSocket.bind(1234);
// 当有数据到达时触发readyRead信号
connect(&udpSocket, &QUdpSocket::readyRead, [&]() {
// 读取数据
QByteArray datagram;
datagram.resize(udpSocket.pendingDatagramSize());
udpSocket.readDatagram(datagram.data(), datagram.size());
// 处理接收到的数据
QString receivedData = QString::fromUtf8(datagram);
qDebug() << "Received data:" << receivedData;
});
// 运行事件循环
QCoreApplication::exec();
```
2. UDP发送:
```cpp
// 创建QUdpSocket对象
QUdpSocket udpSocket;
// 发送数据
QByteArray datagram = "Hello, UDP!";
QHostAddress receiverAddress("127.0.0.1"); // 接收方的IP地址
quint16 receiverPort = 1234; // 接收方的端口号
udpSocket.writeDatagram(datagram, receiverAddress, receiverPort);
```
阅读全文