QT [QT] use to write a simple UDP network broadcast examples

UDP broadcast network
1) the transmitting end, designated port, transmits a broadcast message
   broadcast address: 255.255.255.255
   using the timer, the timing of sending a message
2) reception side: receiving the specified port, receive broadcast messages

 

The sender

ui interface layout

1.pro file to add network module

QT       += core gui network

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

2. Add the header file

#include <QDialog>
#include <QUdpSocket>
#include <QTimer>

3. Add variable function declaration

private slots:
    void on_startButton_clicked();
    void sendMessage();//定义发送信息
private:
    Ui::UdpSender *ui;
private:
    QUdpSocket* udpSocked;//UDP套接字
    QTimer* timer;//定时器
    bool isStarted;//标记是否已经开始广播

4. Add the function code

UdpSender::UdpSender(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::UdpSender)
{
    ui->setupUi(this);
    isStarted = false;
    udpSocked = new QUdpSocket(this);
    timer = new QTimer(this);
    //定时器到时将发送信号timeout
    connect(timer,SIGNAL(timeout()),
                     this,SLOT(sendMessage()));
}

UdpSender::~UdpSender()
{
    delete ui;
}
void UdpSender::on_startButton_clicked()
{
    if(isStarted == false){
        isStarted = true;//开始广播状态
        ui->startButton->setText("停止广播");
        ui->portEdit->setEnabled(false);
        ui->messageEdit->setEnabled(false);
        //开启定时器,每隔1S发送一次消息
        timer->start(1000);
    }
    else{
        isStarted = false;//停止广播状态
        ui->startButton->setText("开始广播");
        ui->portEdit->setEnabled(true);
        ui->messageEdit->setEnabled(true);
        timer->stop();//停止定时器
    }
}
void UdpSender::sendMessage()
{
    qDebug("%s",__func__);
    //获取端口号
    quint16 port = ui->portEdit->text().toInt();
    //获取广播消息字符串
    QString msg = ui->messageEdit->text();
    if(msg == ""){
        return;
    }
    qDebug() << msg;
    //toLocal8Bit():QString-->QByteArray;
    udpSocked->writeDatagram(msg.toLocal8Bit(),
                 QHostAddress::Broadcast,port);
}

 

Receiving end

ui interface layout

1.pro file also add network module

2. Add the header file

#include <QDialog>
#include <QUdpSocket>
#include <QMessageBox>

3. Add variable function declaration

private slots:
    void on_startButton_clicked();
    void messageReceived();
private:
    Ui::UdpReceiver *ui;
private:
    bool isStarted;
    quint16 port;
    QUdpSocket *udpSocket;

4. Add the function code

UdpReceiver::UdpReceiver(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::UdpReceiver)
{
    ui->setupUi(this);
    udpSocket = new QUdpSocket(this);
    isStarted = false;
}

UdpReceiver::~UdpReceiver()
{
    delete ui;
}

void UdpReceiver::on_startButton_clicked()
{
    if(isStarted == false){
        isStarted = true;//开始接收消息
        //获取端口号
        port = ui->portEdit->text().toInt();
        //绑定端口号
        bool result = udpSocket->bind(port);
        if(result == false){
            QMessageBox::information(
                this,"错误:","绑定端口失败!");
            return;
        }
        ui->portEdit->setEnabled(false);
        ui->startButton->setText("停止接收");
        //当套接口有数据到来时将发送readyRead信号
        connect(udpSocket,SIGNAL(readyRead()),
                  this,SLOT(messageReceived()));
    }
    else{
        isStarted = false;//停止接收
        udpSocket->close();
        ui->portEdit->setEnabled(true);
        ui->startButton->setText("开始接收");
    }
}
void UdpReceiver::messageReceived()
{
    qDebug("%s",__func__);
    //判断UDP套接口是否有数据到来
    if(udpSocket->hasPendingDatagrams()){
        QByteArray datagram;
        //获取数据包大小
        datagram.resize(
                udpSocket->pendingDatagramSize());
        //读取数据
        udpSocket->readDatagram(
                 datagram.data(),datagram.size());
        //显示消息到UI界面
        QString msg = datagram.data();
        ui->listWidget->addItem(msg);
    }
}

run

Published 201 original articles · won praise 46 · views 90000 +

Guess you like

Origin blog.csdn.net/rong11417/article/details/104477130