QT(6)-UDP数据收发

一、UDP通信概述

UDP是轻量的、不可靠的、面向数据报、无连接的协议,它可以用于对可靠性要求不高的场合,和TCP通信不同,两个程序之间进行UDP通信无需预先建立持久的socket连接,UDP每次发送数据报都需要指定目标地址和端口。

QUdpSocket类用于实现UDP通信。发送数据报使用writeDatagram()函数,数据报的长度一般小于512字节,每个数据报包含发送者和接收者的IP地址和端口等信息;接收数据报要先用bind()函数绑定一个端口,当有数据传入时会触发readyRead信号,使用readDatagram()函数来读取接收到的数据。

二、UDP单播模式

本文实现的是上位机(PC)向下位机(STM32)发送信息,STM32接收到信息之后回立刻返回一帧信息,上位机接收到信息之后,解析命令得到下位机的IP地址和端口号,并同信息内容一同打印。

先在QT的.pro文件中添加QT += network。

1.接收数据

要实现UDP数据的接收,必须先用bind()函数绑定本机的一个端口,用于监听传入的数据报,解除绑定则使用abort()函数。绑定端口之后,当上位机接收到数据就会触发QUdpSocket类中的readyRead()信号,因此将该信号通过槽函数连接到UDPSocketReadyRead()函数处理接收到的数据。

2.发送数据

使用writeDatagram()函数向下位机发送消息时,需要指定目标地址和端口。QUdpSocket发送的数据报是QByteArray类型,长度一般不超过512字节。

复制代码
/*
*   接收数据
*/
void MainWindow::UDPSocketReadyRead()
{
 
    while(Myudpsocket->hasPendingDatagrams())
    {
        QByteArray Recivedata;
        Recivedata.resize(Myudpsocket->pendingDatagramSize());
        QHostAddress peerAddr;
        quint16 peerPort;
        Myudpsocket->readDatagram(Recivedata.data(), Recivedata.size(), &peerAddr, &peerPort);
        QString str = Recivedata.data();
        QString peer = "[From" + peerAddr.toString() + ":" + QString::number(peerPort) +"]";
        ui->textEdit_recive->setText(peer+str);
    }
}

总结

以下代码已经经过实际的验证,可正常使用!!!

代码h文件

复制代码
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
#include <QtNetwork/QUdpSocket>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QNetworkInterface>
#include <QtNetwork/QNetworkAddressEntry>
 
namespace Ui {
class MainWindow;
}
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
 
public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
 
private slots:
    void UDPSocketReadyRead();
 
    void on_pushButton_UDP_send_clicked();
 
    void on_pushButton_UDP_bind_clicked();
 
private:
    Ui::MainWindow *ui;
 
    QString GetlocalIP();
 
    QUdpSocket *Myudpsocket;
 
};
 
#endif // MAINWINDOW_H

代码c文件

复制代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
 
    /********获取本机IP地址**********/
    QString localIP = GetlocalIP();
    this->setWindowTitle("---本机IP:"+localIP);
    ui->comboBox_localIP->addItem(localIP);
 
    /********本机IP设置**********/
    Myudpsocket = new QUdpSocket(this);
    connect(Myudpsocket, &QUdpSocket::readyRead, this, &MainWindow::UDPSocketReadyRead);
 
}
 
MainWindow::~MainWindow()
{
    Myudpsocket->abort();          //解除绑定
    delete ui;
}
 
/*
*   获取本机IP地址
*/
QString MainWindow::GetlocalIP()
{
    QString strIpAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // 获取第一个本主机的IPv4地址
    int nListSize = ipAddressesList.size();
    for (int i = 0; i < nListSize; ++i)
    {
           if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
               ipAddressesList.at(i).toIPv4Address()) {
               strIpAddress = ipAddressesList.at(i).toString();
               break;
           }
     }
     // 如果没有找到,则以本地IP地址为IP
     if (strIpAddress.isEmpty())
        strIpAddress = QHostAddress(QHostAddress::LocalHost).toString();
     return strIpAddress;
}
 
/*
*   接收数据
*/
void MainWindow::UDPSocketReadyRead()
{
 
    while(Myudpsocket->hasPendingDatagrams())
    {
        QByteArray Recivedata;
        Recivedata.resize(Myudpsocket->pendingDatagramSize());
        QHostAddress peerAddr;
        quint16 peerPort;
        Myudpsocket->readDatagram(Recivedata.data(), Recivedata.size(), &peerAddr, &peerPort);
        QString str = Recivedata.data();
        QString peer = "[From" + peerAddr.toString() + ":" + QString::number(peerPort) +"]";
        ui->textEdit_recive->setText(peer+str);
    }
}
 
/*
*   发送数据
*/
void MainWindow::on_pushButton_UDP_send_clicked()
{
    QHostAddress GoalADDr(QString(ui->comboBox_goalIP->currentText()));
    quint16 GoalPort = ui->spinBox_goalport->value();
    QString sendstr = ui ->textEdit_send->toPlainText();
    QByteArray str = sendstr.toUtf8();
    Myudpsocket->writeDatagram(str, GoalADDr, GoalPort);
//    ui->label_information->setText("send ok!");
}
 
/*
*   绑定端口
*/
void MainWindow::on_pushButton_UDP_bind_clicked()
{
    quint16 port = ui->spinBox_localport->value();
    if(Myudpsocket->bind(port))
    {
        ui->label_information->setText(QString("端口号:%1 绑定成功").arg(port));
    }else {
        ui->label_information->setText(QString("端口号:%1 绑定失败").arg(port));
    }
}
相关推荐
物联网软硬件开发-轨物科技2 小时前
【轨物洞见】什么是产品碳足迹(PCF)?ISO 14067 计算方法与应用场景深度解读
大数据·网络·人工智能
姜鱼问生5 小时前
docker exec 排查容器问题:从日志到进程
运维·网络·数据库·docker·容器
盛世宏博北京5 小时前
工业环境稳定采集:配电室 IP 温湿度变送器 TCP/UDP 通信部署指南
单片机·tcp/ip·udp
qq_543447825 小时前
DNS解析怎么排查?故障处理与运维实用手册
运维·服务器·网络·php
刘马想放假5 小时前
网络链路备份与高可用技术详解:从 Dual-WAN、LACP 到 SD-WAN 与 MPTCP
网络协议
Zelman5 小时前
第07章-数据中心网络
后端·网络协议
威胁猎人7 小时前
网络水军产业风险研究报告
网络
独钓寒江雨7 小时前
路由器单MAC多IP支持功能未开启致业务异常
网络·数通·故障·中兴·m6000·单mac多ip
桀人7 小时前
USART帧格式
网络·stm32·单片机·嵌入式硬件
2301_777998348 小时前
TCP粘包问题:原理、解决方法与UDP为什么没有粘包
网络