溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

QT5實(shí)現(xiàn)UDP通信的示例代碼怎么寫

發(fā)布時間:2021-12-15 18:36:41 來源:億速云 閱讀:199 作者:柒染 欄目:開發(fā)技術(shù)

QT5實(shí)現(xiàn)UDP通信的示例代碼怎么寫,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

前言

該例程經(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ù)報、無連接的協(xié)議,它可以用于對可靠性要求不高的場合,和TCP通信不同,兩個程序之間進(jìn)行UDP通信無需預(yù)先建立持久的socket連接,UDP每次發(fā)送數(shù)據(jù)報都需要指定目標(biāo)地址和端口。
QUdpSocket類用于實(shí)現(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單播模式

QT5實(shí)現(xiàn)UDP通信的示例代碼怎么寫

本文實(shí)現(xiàn)的是上位機(jī)(PC)向下位機(jī)(STM32)發(fā)送信息,STM32接收到信息之后回立刻返回一幀信息,上位機(jī)接收到信息之后,解析命令得到下位機(jī)的IP地址和端口號,并同信息內(nèi)容一同打印。
先在QT的.pro文件中添加QT += network。

1.接收數(shù)據(jù)

要實(shí)現(xiàn)UDP數(shù)據(jù)的接收,必須先用bind()函數(shù)綁定本機(jī)的一個端口,用于監(jiān)聽傳入的數(shù)據(jù)報,解除綁定則使用abort()函數(shù)。綁定端口之后,當(dāng)上位機(jī)接收到數(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ù)向下位機(jī)發(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)過實(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();
    // 獲取第一個本主機(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("端口號:%1 綁定成功").arg(port));
    }else {
        ui->label_information->setText(QString("端口號:%1 綁定失敗").arg(port));
    }
}

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI