QT5實現(xiàn)UDP通信的示例代碼
前言
該例程經(jīng)過實際驗證可以正常使用,只簡單的使用UDP中的單播模式(一對一),其余模式將在后期逐步說明。。。。。。
所用測試系統(tǒng)在同一局域網(wǎng),其中:
QT版本:5.12
PC端UDP模式:單播
UDP通信目標(biāo):基于STM32F4+LWIP協(xié)議的以太網(wǎng)接口
一、UDP通信概述
UDP是輕量的、不可靠的、面向數(shù)據(jù)報、無連接的協(xié)議,它可以用于對可靠性要求不高的場合,和TCP通信不同,兩個程序之間進行UDP通信無需預(yù)先建立持久的socket連接,UDP每次發(fā)送數(shù)據(jù)報都需要指定目標(biāo)地址和端口。
QUdpSocket類用于實現(xiàn)UDP通信。發(fā)送數(shù)據(jù)報使用writeDatagram()函數(shù),數(shù)據(jù)報的長度一般小于512字節(jié),每個數(shù)據(jù)報包含發(fā)送者和接收者的IP地址和端口等信息;接收數(shù)據(jù)報要先用bind()函數(shù)綁定一個端口,當(dāng)有數(shù)據(jù)傳入時會觸發(fā)readyRead信號,使用readDatagram()函數(shù)來讀取接收到的數(shù)據(jù)。
二、UDP單播模式
本文實現(xiàn)的是上位機(PC)向下位機(STM32)發(fā)送信息,STM32接收到信息之后回立刻返回一幀信息,上位機接收到信息之后,解析命令得到下位機的IP地址和端口號,并同信息內(nèi)容一同打印。
先在QT的.pro文件中添加QT += network。
1.接收數(shù)據(jù)
要實現(xiàn)UDP數(shù)據(jù)的接收,必須先用bind()函數(shù)綁定本機的一個端口,用于監(jiān)聽傳入的數(shù)據(jù)報,解除綁定則使用abort()函數(shù)。綁定端口之后,當(dāng)上位機接收到數(shù)據(jù)就會觸發(fā)QUdpSocket類中的readyRead()信號,因此將該信號通過槽函數(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ù)向下位機發(fā)送消息時,需要指定目標(biāo)地址和端口。QUdpSocket發(fā)送的數(shù)據(jù)報是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)過實際的驗證,可正常使用?。?!
代碼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設(shè)置**********/ 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; } /* * 接收數(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("端口號:%1 綁定成功").arg(port)); }else { ui->label_information->setText(QString("端口號:%1 綁定失敗").arg(port)); } }
到此這篇關(guān)于QT5實現(xiàn)UDP通信的示例代碼的文章就介紹到這了,更多相關(guān)QT5 UDP通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言中access/_access函數(shù)的使用實例詳解
本文通過實例代碼給大家介紹了C語言中access/_access函數(shù)的使用,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09C++實現(xiàn)將s16le的音頻流轉(zhuǎn)換為float類型
這篇文章主要為大家詳細(xì)介紹了如何利用C++實現(xiàn)將s16le的音頻流轉(zhuǎn)換為float類型,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-04-04使用WindowsAPI實現(xiàn)播放PCM音頻的方法
這篇文章主要介紹了使用WindowsAPI實現(xiàn)播放PCM音頻的方法,很實用的一個功能,需要的朋友可以參考下2014-08-08C++實現(xiàn)圖書管理系統(tǒng)課程設(shè)計
這篇文章主要為大家詳細(xì)介紹了C++實現(xiàn)圖書管理系統(tǒng)課程設(shè)計,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03C語言詳細(xì)分析貪心策略中最小生成樹的Prime算法設(shè)計與實現(xiàn)
最小生成樹的問題還是比較熱門的,最經(jīng)典的莫過于Prime算法和Kruskal算法了,這篇博文我會詳細(xì)講解Prime算法的設(shè)計思想與具體代碼的實現(xiàn),不要求數(shù)據(jù)結(jié)構(gòu)學(xué)的有多好,只要跟著我的思路來,一步一步的分析,調(diào)試,終能成就自己,那就讓我們開始吧2022-05-05