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());
}
}

相关推荐
火山上的企鹅7 小时前
Qt Quick 之动态旋转刻度盘(无人机中指南针 Demo )
qt·无人机·cocos2d
是小峰呀9 小时前
QT+opencv+yolov8推理
开发语言·qt·yolo
GUIQU.9 小时前
【QT】概述
开发语言·c++·qt
茉莉玫瑰花茶9 小时前
Qt 常用控件 - 5
开发语言·qt
残醉11 小时前
QT自定义控件
qt
啊森要自信1 天前
【QT】常⽤控件详解(四)常用显示类控件类 Label && LCDNumber && ProgressBar && Calendar Widget
开发语言·数据库·c++·qt·qt6.3
Simple_core1 天前
qt贝塞尔曲线演示工具
开发语言·qt
sannianji1 天前
qt 采用movetothread在应用程序gui关闭时如何正确退出。
开发语言·qt
幽迷狂1 天前
AFSIM入门教程03.03:更新所有依赖库版本
c++·qt·仿真·osgearth·osg·军事·afsim