QT UDP发送和接收广播报文

这几天整QT UDP的发送和接收,参考了很多的博客文章。只是觉得都不是很详细,所以我今天给个例子:

#Client.pro

#-------------------------------------------------
#
# Project created by QtCreator 2019-12-23T13:54:29
#
#-------------------------------------------------

QT       += core gui
QT       += network

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = Client
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

CONFIG += c++11

SOURCES += \
        main.cpp \
        mainwindow.cpp

HEADERS += \
        mainwindow.h

FORMS += \
        mainwindow.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

//Client.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QStandardItemModel>
#include <QList>
#include <QStringList>
#include <QtNetwork/QUdpSocket>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_pushButton_search_clicked();

    void on_pushButton_exit_clicked();

    void on_tableView_Net_doubleClicked(const QModelIndex &index);

    void readyRead_slot();

private:
    Ui::MainWindow *ui;
    QUdpSocket *updsock;
    QUdpSocket *udp_recive;
    QStandardItemModel *model_search;
    QStringList stringlist;
};

#endif // MAINWINDOW_H

//Client.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtNetwork/QNetworkAddressEntry>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("Client");

    QStandardItemModel *model = new QStandardItemModel;
    QString Ip;
    int i = 0;
    model->setHorizontalHeaderLabels(QStringList("IP"));
    QList<QNetworkInterface> networkInterface = QNetworkInterface::allInterfaces();
    for (QList<QNetworkInterface>::const_iterator it = networkInterface.constBegin(); it != networkInterface.constEnd(); ++it)
    {
        //获取连接地址列表
        QList<QNetworkAddressEntry> addressEntriesList = (*it).addressEntries();
        for (QList<QNetworkAddressEntry>::const_iterator jIt = addressEntriesList.constBegin(); jIt != addressEntriesList.constEnd(); ++jIt)
        {
            Ip = (*jIt).ip().toString();
            if(Ip.indexOf('.') > 0 && Ip != "127.0.0.1")
            {
                model->setItem(i,0,new QStandardItem(Ip));
                i++;
            }
        }
    }
    ui->tableView_Net->setModel(model);
    ui->tableView_Net->setColumnWidth(0, ui->tableView_Net->width());
    ui->stackedWidget->setCurrentIndex(0);

    this->model_search = new QStandardItemModel;
    this->model_search->setColumnCount(4);
    this->stringlist.append("IP");
    this->stringlist.append("掩码");
    this->stringlist.append("网关");
    this->stringlist.append("MAC");
    this->model_search->setHorizontalHeaderLabels(this->stringlist);
    ui->tableView->setModel(this->model_search);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_search_clicked()
{
    QString str = "AYu";
    this->updsock->writeDatagram(str.toLatin1(),QHostAddress::Broadcast,56169);
}

void MainWindow::on_pushButton_exit_clicked()
{
    this->close();
}

void MainWindow::readyRead_slot()
{
    while (this->updsock->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(this->updsock->pendingDatagramSize());
        this->updsock->readDatagram(datagram.data(),datagram.size());
        QString message(datagram);
        qDebug()<<message<<endl;
    }
}

void MainWindow::on_tableView_Net_doubleClicked(const QModelIndex &index)
{
    this->updsock = new QUdpSocket;

    this->updsock->open(QIODevice::ReadWrite);
    this->updsock->bind(QHostAddress(index.data().toString()),56170);

    this->connect(this->updsock,SIGNAL(readyRead()),this,SLOT(readyRead_slot()));
    ui->stackedWidget->setCurrentIndex(1);
}

以下是一个基于 QtUDP 线程实现发送接收文件的示例代码: ```cpp // 文件发送方的代码 class UdpSender : public QObject { Q_OBJECT public: UdpSender(QObject* parent = nullptr) : QObject(parent) {} public slots: void sendFile(const QString& filePath, const QHostAddress& address, quint16 port) { QFile file(filePath); if (!file.open(QIODevice::ReadOnly)) { qWarning() << "Failed to open file:" << filePath; return; } QUdpSocket socket; while (!file.atEnd()) { QByteArray data = file.read(8192); // 每次读取 8KB 数据 socket.writeDatagram(data, address, port); socket.waitForBytesWritten(); } qInfo() << "File sent successfully."; } }; // 文件接收方的代码 class UdpReceiver : public QObject { Q_OBJECT public: UdpReceiver(QObject* parent = nullptr) : QObject(parent) {} public slots: void receiveFile(const QString& filePath, quint16 port) { QFile file(filePath); if (!file.open(QIODevice::WriteOnly)) { qWarning() << "Failed to open file:" << filePath; return; } QUdpSocket socket; socket.bind(QHostAddress::AnyIPv4, port); while (socket.waitForReadyRead()) { while (socket.hasPendingDatagrams()) { QByteArray data; data.resize(socket.pendingDatagramSize()); socket.readDatagram(data.data(), data.size()); file.write(data); } } qInfo() << "File received successfully."; } }; ``` 在此示例中,`UdpSender` 类用于发送文件,`UdpReceiver` 类用于接收文件。其中,`UdpSender::sendFile()` 方法将文件分块读取并逐一发送,`UdpReceiver::receiveFile()` 方法则不断等待接收数据,直到收到完整的文件为止。 你可以在自己的代码中使用这些类来实现 UDP 文件传输功能。需要注意的是,由于 UDP 是无连接的协议,因此在发送接收数据时需要确保数据的完整性和正确性。你可以通过添加一些校验码或者确认机制来实现这一点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南波儿万

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值