对qt代码的 udp广播学习
简单学习在qt下 UDP广告的代码
#include "mainwindow.h" #include "ui_mainwindow.h" //引用文件必须 #include "QtNetwork/qudpsocket.h" #include "QtNetwork/qhostaddress.h" QUdpSocket *receiver; //接收端的 QUdpSocket *clinet; //发送端 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { clinet =new QUdpSocket(this); receiver = new QUdpSocket(this); //初始化 receiver->bind(2425,QUdpSocket::ShareAddress); //接收端必须处于邦定状态(QUdpSocket::ShareAddress) connect(receiver, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams())); //建立信号 readyread引发readPendingDatagrams ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::readPendingDatagrams() { qDebug("---------进入收信息----------"); //检测是不是有信息到来 while (receiver->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(receiver->pendingDatagramSize()); //获取信息长度 receiver->readDatagram(datagram.data(), datagram.size()); //读到缓冲 ui->plainTextEdit->setPlainText(ui->plainTextEdit->document()->toPlainText()+datagram.data()); } } void MainWindow::on_pushButton_clicked() { QByteArray str="hi my fukun\n"; clinet->writeDatagram(str.data(),str.size(),QHostAddress::Broadcast,2425); //发送端发送数据发送不需要邦定 }
除了上面的内容,在编译时记得在pro文件中加上
QT += network
最终效果如下。