qt中使用UDP通信 代码
时间: 2024-05-23 16:15:35 浏览: 140
Qt中的udp通信
可以参考以下代码:
// 创建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;
}
});
阅读全文