QUdpSocket发送组播和接受组播数据

需要写一个发送组播的窗口测试程序,就想着顺便也接受显示出来下

QHostAddress address(ip);

udpSend.bind(QHostAddress::AnyIPv4,port,QUdpSocket::ShareAddress);//这里绑定如果注释了也没有问题,组播数据还是可以发送出去,程序运行时会报错

QUdpSocket::leaveMulticastGroup() called on a QUdpSocket when not in QUdpSocket::BoundState

udpSend.leaveMulticastGroup(address);

udpSend.joinMulticastGroup(address);

udpReciver.bind(QHostAddress::AnyIPv4,port,QUdpSocket::ShareAddress);//接受的得一定要绑定

udpReciver.leaveMulticastGroup(address);

udpReciver.joinMulticastGroup(address);

disconnect(&udpReciver, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));

connect(&udpReciver, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));

如果在程序中发送和接受都绑定,则一定要都用QUdpSocket::ShareAddress

void Widget::readPendingDatagrams()
{
while (udpReciver.hasPendingDatagrams())
{
QByteArray data;
data.resize(udpReciver.pendingDatagramSize());//这里data一定要resize,不然读不出数据
int len = udpReciver.readDatagram(data.data(),udpReciver.size());//这里一定不要使用readAll(),会报错 QIODevice::read (QUdpSocket): device not open
qDebug() << data.toHex();
ui->textEdit->append(data.toHex().constData());
}
}

相关推荐
蓝祁子yoky14 小时前
Qt学习日记 Day15:网络编程(二)- UDP基础
网络·qt·学习
读书札记202215 小时前
Qt UTF-8和UTF-8(BOM)
开发语言·qt
ShineWinsu15 小时前
对于Qt:QProgressBar常见属性的解析
开发语言·c++·qt·进度条·gui·定时器·qprogressbar
ShineWinsu15 小时前
对于Qt:QLCDNumber常见属性以及QTimer的解析
服务器·数据库·c++·qt·gui·qtimer·qlcdnumber
听风吹等浪起1 天前
第26章:ViT+InceptionDW+FocalLoss改进|CT骨折影像二分类完整Pytorch实现(含PyQt5推理GUI)
pytorch·qt·分类
ShineWinsu1 天前
对于Qt:QRadioButton常见属性以及QButtonGroup的解析
数据库·c++·qt·microsoft·gui·qradiobutton·qbuttongroup
sycmancia1 天前
Qml——Image和AnimatedImage使用
qt
lhbweilai1 天前
QT(了解各个控件和布局)上
数据库·qt
ShineWinsu2 天前
对于Qt:QLabel常见属性的解析
c++·qt·面试·笔试·gui·标签·qlabel
小徐不徐说2 天前
数据库存储基础:理解表结构、主键、事务与 BLOB
开发语言·数据库·c++·qt·程序设计