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);
}

发布了23 篇原创文章 · 获赞 27 · 访问量 1156

猜你喜欢

转载自blog.csdn.net/BLUCEJIE/article/details/103677171