IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> QT UDP网络广播 -> 正文阅读

[网络协议]QT UDP网络广播

Sender

senderdialog.h

#ifndef SENDERDIALOG_H
#define SENDERDIALOG_H

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

namespace Ui {
class SenderDialog;
}

class SenderDialog : public QDialog
{
    Q_OBJECT

public:
    explicit SenderDialog(QWidget *parent = 0);
    ~SenderDialog();

private slots:
    //开始广播按钮对应的槽函数
    void on_pushButton_clicked();
    //定时器发送广播消息的槽函数
    void sendMessage();
private:
    Ui::SenderDialog *ui;
    bool isStarted;//标记:true(开始广播)/false(停止广播)
    QUdpSocket* udpSocket;//通信的UDP套接字
    QTimer* timer;//定时器
};

#endif // SENDERDIALOG_H

senderdialog.cpp

#include "senderdialog.h"
#include "ui_senderdialog.h"

SenderDialog::SenderDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SenderDialog)
{
    ui->setupUi(this);
    isStarted = false;//初始化状态:未开始广播
    udpSocket = new QUdpSocket(this);//创建UDP套接字
    timer = new QTimer(this);//创建定时器
    //定时器到时发送信号timeout()
    connect(timer,SIGNAL(timeout()),this,SLOT(sendMessage()));
}

SenderDialog::~SenderDialog()
{
    delete ui;
}
//开始广播按钮对应的槽函数
void SenderDialog::on_pushButton_clicked()
{
    if(isStarted == false){
        isStarted = true;//开始广播
        ui->pushButton->setText("停止广播");
        ui->messageEdit->setEnabled(false);//禁用消息输入
        ui->portEdit->setEnabled(false);//禁用端口输入
        timer->start(1000);//开启定时器,每隔1秒广播一次
    }
    else{
        isStarted = false;//停止广播
        ui->pushButton->setText("开始广播");
        ui->messageEdit->setEnabled(true);//恢复消息输入
        ui->portEdit->setEnabled(true);//恢复端口输入
        timer->stop();//关闭定时器,停止广播
    }
}
//定时器发送广播消息的槽函数
void SenderDialog::sendMessage()
{
    //获取广播消息
    QString msg = ui->messageEdit->text();
    if(msg == ""){
        return;
    }
    //获取广播端口
    quint16 port = ui->portEdit->text().toShort();
    if(port<1024){
        return;
    }
    //通过udp套接字发送广播消息
    //参数:
    //1)发送消息数据缓冲区(QByteArrage)
    //2)广播地址(QHostAddress),Broadcast("255.255.255.255")
    //3)广播端口(quint16)
    udpSocket->writeDatagram(msg.toUtf8(),QHostAddress::Broadcast,port);
}

main.cpp

#include "senderdialog.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    SenderDialog w;
    w.show();

    return a.exec();
}

Receiver

receiver.h

#ifndef RECEIVERDIALOG_H
#define RECEIVERDIALOG_H

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

namespace Ui {
class ReceiverDialog;
}

class ReceiverDialog : public QDialog
{
    Q_OBJECT

public:
    explicit ReceiverDialog(QWidget *parent = 0);
    ~ReceiverDialog();

private slots:
    //开始接收按钮对应的槽函数
    void on_pushButton_clicked();
    //接收广播消息的槽函数
    void receiveMessage();
private:
    Ui::ReceiverDialog *ui;
    bool isStarted;//标记,true(开始接收)/false(停止接收)
    QUdpSocket* udpSocket;//通信套接字
};

#endif // RECEIVERDIALOG_H

receiverdialog.cpp

#include "receiverdialog.h"
#include "ui_receiverdialog.h"

ReceiverDialog::ReceiverDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ReceiverDialog)
{
    ui->setupUi(this);
    isStarted = false;//初始化状态标记
    udpSocket = new QUdpSocket(this);//创建UDP通信套接字
}

ReceiverDialog::~ReceiverDialog()
{
    delete ui;
}
//开始接收按钮对应的槽函数
void ReceiverDialog::on_pushButton_clicked()
{
    if(isStarted == false){
        isStarted = true;//开始接收广播消息
        ui->pushButton->setText("停止接收");
        //获取广播端口
        quint16 port = ui->lineEdit->text().toShort();
        ui->lineEdit->setEnabled(false);//禁用端口输入
        //绑定接收消息端口
        //参数:IP地址(Any->"0.0.0.0"),端口号
        if(udpSocket->bind(QHostAddress::Any,port)==false){
            QMessageBox::critical(this,"Error","端口号错误!");
            return;
        }
        else{
            qDebug("绑定端口成功!");
            //当有广播消息到来时,发送信号readyRead
            connect(udpSocket,SIGNAL(readyRead()),
                    this,SLOT(receiveMessage()));
        }
    }
    else{
        isStarted = false;//停止接收广播消息
        ui->pushButton->setText("开始接收");
        udpSocket->close();//关闭套接字,停止接收广播消息
        ui->lineEdit->setEnabled(true);//恢复端口输入
    }
}
//接收广播消息的槽函数
void ReceiverDialog::receiveMessage()
{
    //hasPendingDatagrams:判断udp套接字是否等到读取的消息
    while(udpSocket->hasPendingDatagrams()){
        //准备接收广播消息的缓冲区
        QByteArray buf;
        //pendingDatagramSize:获取等待读取数据包的字节数
        buf.resize(udpSocket->pendingDatagramSize());
        //读取数据包,参数:
        //1)接收数据缓冲区首地址(char*),data():将QByteArray转换为char*
        //2)要读取数据包大小
        udpSocket->readDatagram(buf.data(),buf.size());
        //显示消息
        ui->listWidget->addItem(buf);
        ui->listWidget->scrollToBottom();
    }
}

main.cpp

#include "receiverdialog.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    ReceiverDialog w;
    w.show();

    return a.exec();
}
  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-07-22 23:06:44  更:2021-07-22 23:07:09 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/7 10:08:52-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码