#include "mainwindow.h" #include "ui_mainwindow.h" #include <QThread> #define UDP_PORT1 31002 QHostAddress MulticastGroup = QHostAddress("239.192.1.1"); MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setWindowTitle("udp test"); udp10002 = new QUdpSocket(this); udp10002->bind(QHostAddress::AnyIPv4, UDP_PORT1,QAbstractSocket::ShareAddress); udp10002->joinMulticastGroup(MulticastGroup); udp10002->setSocketOption( udp10002->MulticastLoopbackOption,0); connect(udp10002, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams10002())); } void MainWindow::resizeEvent(QResizeEvent *) { ui->horizontalLayoutWidget->resize(this->width(),this->height()); } MainWindow::~MainWindow() { delete ui; udp10002->close(); qDebug()<<"close " <<UDP_PORT1; udp10002->leaveMulticastGroup(MulticastGroup); } void MainWindow::readPendingDatagrams10002() { while (udp10002->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(udp10002->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; udp10002->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort); qDebug()<<"read:"<<sender<<senderPort<<datagram; udp10002->writeDatagram("HHHHHHHHHHHHHHH",sender,senderPort); udp10002->writeDatagram("HHHHHHHHHHHHHHH",MulticastGroup,31003); } }
时间: 2024-10-06 04:06:30