qt中使用UDP通信 代码
时间: 2024-05-23 18:15:35 浏览: 145
QT之UDP通信的实现,UDP编程.-综合文档
5星 · 资源好评率100%
可以参考以下代码:
// 创建socket
QUdpSocket *udpSocket = new QUdpSocket(this);
// 绑定端口
udpSocket->bind(port);
// 发送数据
QByteArray data = "Hello World";
QHostAddress address = QHostAddress::LocalHost;
udpSocket->writeDatagram(data, address, port);
// 接收数据
connect(udpSocket, &QUdpSocket::readyRead, this, [=]() {
while (udpSocket->hasPendingDatagrams()) {
QByteArray data;
QHostAddress senderAddress;
quint16 senderPort;
data.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(data.data(), data.size(), &senderAddress, &senderPort);
qDebug() << "Received data:" << data;
}
});
阅读全文