QT5實(shí)現(xiàn)UDP通信的示例代碼
前言
該例程經(jīng)過(guò)實(shí)際驗(yàn)證可以正常使用,只簡(jiǎn)單的使用UDP中的單播模式(一對(duì)一),其余模式將在后期逐步說(shuō)明。。。。。。
所用測(cè)試系統(tǒng)在同一局域網(wǎng),其中:
QT版本:5.12
PC端UDP模式:?jiǎn)尾?br />
UDP通信目標(biāo):基于STM32F4+LWIP協(xié)議的以太網(wǎng)接口
一、UDP通信概述
UDP是輕量的、不可靠的、面向數(shù)據(jù)報(bào)、無(wú)連接的協(xié)議,它可以用于對(duì)可靠性要求不高的場(chǎng)合,和TCP通信不同,兩個(gè)程序之間進(jìn)行UDP通信無(wú)需預(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)的長(zhǎng)度一般小于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ù)來(lái)讀取接收到的數(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)聽(tīng)傳入的數(shù)據(jù)報(bào),解除綁定則使用abort()函數(shù)。綁定端口之后,當(dāng)上位機(jī)接收到數(shù)據(jù)就會(huì)觸發(fā)QUdpSocket類中的readyRead()信號(hào),因此將該信號(hào)通過(guò)槽函數(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類型,長(zhǎng)度一般不超過(guò)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)過(guò)實(shí)際的驗(yàn)證,可正常使用?。?!
代碼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;
}
}
// 如果沒(méi)有找到,則以本地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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Qt實(shí)現(xiàn)簡(jiǎn)單的TCP通信
- QT編寫(xiě)tcp通信工具(Client篇)
- QT編寫(xiě)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)簡(jiǎn)單UDP通信
- QT5實(shí)現(xiàn)簡(jiǎn)單的TCP通信的實(shí)現(xiàn)
- 基于QT的TCP通信服務(wù)的實(shí)現(xiàn)
- QT串口通信的實(shí)現(xiàn)方法
- Qt實(shí)現(xiàn)進(jìn)程間通信
相關(guān)文章
C++ 遞歸遍歷文件并計(jì)算MD5的實(shí)例代碼
在本篇文章里小編給大家整理的是一篇關(guān)于C++ 遞歸遍歷文件并計(jì)算MD5的實(shí)例代碼,有興趣的朋友們可以學(xué)習(xí)參考下。2021-07-07
C語(yǔ)言中的數(shù)組和指針匯編代碼分析實(shí)例
C++面試題之結(jié)構(gòu)體內(nèi)存對(duì)齊計(jì)算問(wèn)題總結(jié)大全
淺談Qt中使用CEF的幾個(gè)要點(diǎn)(Windows下)
OpenSSL使用AES實(shí)現(xiàn)文件加解密功能

