首页 > 作文

QT5实现UDP通信的示例代码

更新时间:2023-04-04 03:01:53 阅读: 评论:0

目录
前言 一、udp通信概述 二、udp单播模式1.接收数据 2.发送数据 总结 代码h文件 代码c文件

前言

该例程经过实际验证可以正常使用,只简单的使用udp中的单播模式(一对一),其余模式将在后期逐步说明。。。。。。
所用测试系统在同一局域网,其中:
qt版本:5.12
pc端udp模式:单播
udp通信目标:基于stm32f4+lwip协议的以太网接口

一、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()函数处理接收到的数据。

/**   接收数据*/void mainwindow::udpsocketreadyread(){    while(myudpsocket->haspendingdatagrams())    {        qbytearray recivedata;        recivedata.resize(myudpsocket->pendingdatagramsize());        qhostaddress peer台式机电源推荐addr;        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->ttext(peer+str);    }}

2.发送数据

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

/**   发送数据*/void mainwindow::on_pushbutton_udp_nd_clicked(){    qhostaddress goaladdr(qstring(ui->combobox_goalip->currenttext()));    quint16 goalport = ui->spinbox_goalport->value();    qstring ndstr = ui ->textedit_nd->toplaintext();    qbytearray str = ndstr.toutf8();    myudpsocket->writedatagram(str, goaladdr, goalport);//    ui->label_information->ttext("nd ok!");}

总结

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

代码h文件

#ifndef mainwindow_h#define mainwindow_h#include <qma安的意思inwindow>#include <qtnetwork/qudpsocket>#include <qtnetwork/qhostaddress>#include <qtnetwork/qnetworkinterface>#include <qtnetwork/qnetworkaddres考研初试ntry>namespace ui {class mainwindow;}class mainwindow : public qmainwindow{    q_objectpublic:    explicit mainwindow(qwidget *parent = nullptr);    ~mainwindow();private slots:    void udpsocketreadyread();    void on_pushbutton_udp_nd_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->tupui(this);    /********获取本机ip地址**********/    qstring localip = getlocalip();    this->twindowtitle("---本机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> ipaddresslist = qnetworkinterface::alladdress();    // 获取第一个本主机的ipv4地址    int nlistsize = ipaddresslist.size();    for (int i = 0; i < nlistsize; ++i)    {           if (ipaddresslist.at(i) != qhostaddress::localhost &&               ipaddresslist.at(i).toipv4address()) {               stripaddress = ipaddresslist.at(i).tostring();               break;           }     }     // 如果没有找到,则以本地ip地址为ip     if (stripaddress.impty())        stripaddress = qhostaddress(qhostaddress::localhost).tostring();     retur再见你好吗n 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->ttext(peer+str);    }}/**   发送数据*/void mainwindow::on_pushbutton_udp_nd_clicked(){    qhostaddress goaladdr(qstring(ui->combobox_goalip->currenttext()));    quint16 goalport = ui->spinbox_goalport->value();    qstring ndstr = ui ->textedit_nd->toplaintext();    qbytearray str = ndstr.toutf8();    myudpsocket->writedatagram(str, goaladdr, goalport);//    ui->label_information->ttext("nd ok!");}/**   绑定端口*/void mainwindow::on_pushbutton_udp_bind_clicked(){    quint16 port = ui经典长篇笑话->spinbox_localport->value();    if(myudpsocket->bind(port))    {        ui->label_information->ttext(qstring("端口号:%1 绑定成功").arg(port));    }el {        ui->label_information->ttext(qstring("端口号:%1 绑定失败").arg(port));    }}

到此这篇关于qt5实现udp通信的示例代码的文章就介绍到这了,更多相关qt5 udp通信内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

本文发布于:2023-04-04 03:01:51,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/20d79311a5c139cfceea1d14fffe55e1.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:QT5实现UDP通信的示例代码.doc

本文 PDF 下载地址:QT5实现UDP通信的示例代码.pdf

标签:数据   函数   绑定   端口
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图