Qt udp 点对点通信demo
时间: 2023-07-10 22:32:25 浏览: 158
以下是使用Qt实现UDP点对点通信的示例代码:
Sender端代码:
```cpp
#include <QtNetwork/QUdpSocket>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QUdpSocket socket;
// 绑定socket到本地地址和端口
socket.bind(QHostAddress::AnyIPv4, 8888);
// 发送UDP数据报
QByteArray datagram = "hello world";
QHostAddress receiverAddress("127.0.0.1");
quint16 receiverPort = 9999;
socket.writeDatagram(datagram, receiverAddress, receiverPort);
return a.exec();
}
```
Receiver端代码:
```cpp
#include <QtNetwork/QUdpSocket>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QUdpSocket socket;
// 绑定socket到本地地址和端口
socket.bind(QHostAddress::AnyIPv4, 9999);
// 接收UDP数据报
while (true) {
QByteArray datagram;
QHostAddress sender;
quint16 senderPort;
socket.waitForReadyRead(-1);
datagram.resize(socket.pendingDatagramSize());
socket.readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
qDebug() << "Received datagram from" << sender.toString() << ":" << senderPort << datagram;
}
return a.exec();
}
```
在这个示例中,Sender端将UDP数据报发送到Receiver端的IP地址和端口号,Receiver端通过等待socket的数据可读信号和调用`readDatagram()`函数来接收数据报,并打印出发送数据报的主机地址、端口号和数据内容。
需要注意的是,在本示例中,Receiver端的端口号为9999,Sender端的端口号为8888,需要根据实际情况进行调整,确保Receiver端绑定的地址和端口与Sender端发送的地址和端口一致。
阅读全文