QT5實(shí)現(xiàn)UDP通信的示例代碼
前言
該例程經(jīng)過實(shí)際驗(yàn)證可以正常使用,只簡單的使用UDP中的單播模式(一對一),其余模式將在后期逐步說明。。。。。。
所用測試系統(tǒng)在同一局域網(wǎng),其中:
QT版本:5.12
PC端UDP模式:單播
UDP通信目標(biāo):基于STM32F4+LWIP協(xié)議的以太網(wǎng)接口
一、UDP通信概述
UDP是輕量的、不可靠的、面向數(shù)據(jù)報(bào)、無連接的協(xié)議,它可以用于對可靠性要求不高的場合,和TCP通信不同,兩個(gè)程序之間進(jìn)行UDP通信無需預(yù)先建立持久的socket連接,UDP每次發(fā)送數(shù)據(jù)報(bào)都需要指定目標(biāo)地址和端口。
QUdpSocket類用于實(shí)現(xiàn)UDP通信。發(fā)送數(shù)據(jù)報(bào)使用writeDatagram()函數(shù),數(shù)據(jù)報(bào)的長度一般小于512字節(jié),每個(gè)數(shù)據(jù)報(bào)包含發(fā)送者和接收者的IP地址和端口等信息;接收數(shù)據(jù)報(bào)要先用bind()函數(shù)綁定一個(gè)端口,當(dāng)有數(shù)據(jù)傳入時(shí)會(huì)觸發(fā)readyRead信號(hào),使用readDatagram()函數(shù)來讀取接收到的數(shù)據(jù)。
二、UDP單播模式

本文實(shí)現(xiàn)的是上位機(jī)(PC)向下位機(jī)(STM32)發(fā)送信息,STM32接收到信息之后回立刻返回一幀信息,上位機(jī)接收到信息之后,解析命令得到下位機(jī)的IP地址和端口號(hào),并同信息內(nèi)容一同打印。
先在QT的.pro文件中添加QT += network。
1.接收數(shù)據(jù)
要實(shí)現(xiàn)UDP數(shù)據(jù)的接收,必須先用bind()函數(shù)綁定本機(jī)的一個(gè)端口,用于監(jiān)聽傳入的數(shù)據(jù)報(bào),解除綁定則使用abort()函數(shù)。綁定端口之后,當(dāng)上位機(jī)接收到數(shù)據(jù)就會(huì)觸發(fā)QUdpSocket類中的readyRead()信號(hào),因此將該信號(hào)通過槽函數(shù)連接到UDPSocketReadyRead()函數(shù)處理接收到的數(shù)據(jù)。
/*
* 接收數(shù)據(jù)
*/
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);
}
}
2.發(fā)送數(shù)據(jù)
使用writeDatagram()函數(shù)向下位機(jī)發(fā)送消息時(shí),需要指定目標(biāo)地址和端口。QUdpSocket發(fā)送的數(shù)據(jù)報(bào)是QByteArray類型,長度一般不超過512字節(jié)。
/*
* 發(fā)送數(shù)據(jù)
*/
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!");
}
總結(jié)
以下代碼已經(jīng)經(jīng)過實(shí)際的驗(yàn)證,可正常使用?。。?/p>
代碼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);
/********獲取本機(jī)IP地址**********/
QString localIP = GetlocalIP();
this->setWindowTitle("---本機(jī)IP:"+localIP);
ui->comboBox_localIP->addItem(localIP);
/********本機(jī)IP設(shè)置**********/
Myudpsocket = new QUdpSocket(this);
connect(Myudpsocket, &QUdpSocket::readyRead, this, &MainWindow::UDPSocketReadyRead);
}
MainWindow::~MainWindow()
{
Myudpsocket->abort(); //解除綁定
delete ui;
}
/*
* 獲取本機(jī)IP地址
*/
QString MainWindow::GetlocalIP()
{
QString strIpAddress;
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
// 獲取第一個(gè)本主機(jī)的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;
}
/*
* 接收數(shù)據(jù)
*/
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);
}
}
/*
* 發(fā)送數(shù)據(jù)
*/
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("端口號(hào):%1 綁定成功").arg(port));
}else {
ui->label_information->setText(QString("端口號(hào):%1 綁定失敗").arg(port));
}
}
到此這篇關(guān)于QT5實(shí)現(xiàn)UDP通信的示例代碼的文章就介紹到這了,更多相關(guān)QT5 UDP通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Qt實(shí)現(xiàn)簡單的TCP通信
- QT編寫tcp通信工具(Client篇)
- QT編寫tcp通信工具(Server端)
- QT網(wǎng)絡(luò)通信TCP客戶端實(shí)現(xiàn)詳解
- Qt?TCP網(wǎng)絡(luò)通信學(xué)習(xí)
- Qt網(wǎng)絡(luò)編程實(shí)現(xiàn)TCP通信
- Qt實(shí)現(xiàn)簡單UDP通信
- QT5實(shí)現(xiàn)簡單的TCP通信的實(shí)現(xiàn)
- 基于QT的TCP通信服務(wù)的實(shí)現(xiàn)
- QT串口通信的實(shí)現(xiàn)方法
- Qt實(shí)現(xiàn)進(jìn)程間通信
相關(guān)文章
C語言中access/_access函數(shù)的使用實(shí)例詳解
本文通過實(shí)例代碼給大家介紹了C語言中access/_access函數(shù)的使用,代碼簡單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09
C++實(shí)現(xiàn)將s16le的音頻流轉(zhuǎn)換為float類型
這篇文章主要為大家詳細(xì)介紹了如何利用C++實(shí)現(xiàn)將s16le的音頻流轉(zhuǎn)換為float類型,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-04-04
使用WindowsAPI實(shí)現(xiàn)播放PCM音頻的方法
這篇文章主要介紹了使用WindowsAPI實(shí)現(xiàn)播放PCM音頻的方法,很實(shí)用的一個(gè)功能,需要的朋友可以參考下2014-08-08
C++實(shí)現(xiàn)圖書管理系統(tǒng)課程設(shè)計(jì)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)圖書管理系統(tǒng)課程設(shè)計(jì),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
C語言詳細(xì)分析貪心策略中最小生成樹的Prime算法設(shè)計(jì)與實(shí)現(xiàn)
最小生成樹的問題還是比較熱門的,最經(jīng)典的莫過于Prime算法和Kruskal算法了,這篇博文我會(huì)詳細(xì)講解Prime算法的設(shè)計(jì)思想與具體代碼的實(shí)現(xiàn),不要求數(shù)據(jù)結(jié)構(gòu)學(xué)的有多好,只要跟著我的思路來,一步一步的分析,調(diào)試,終能成就自己,那就讓我們開始吧2022-05-05

