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

相关推荐
用户805533698037 小时前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner8 小时前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz5 天前
QML Hello World 入门示例
qt
xcyxiner8 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner9 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner9 天前
DicomViewer (添加模型类)3
qt
xcyxiner10 天前
DicomViewer (目录调整) 2
qt
xcyxiner10 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
桥田智能12 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G12 天前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt