QT之UDP通信

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/fengweibo112/article/details/100519466

概述

使用QT Creator进行UDP发送和接收功能的windows上位机开发。

工程创建

新建QT桌面应用程序。
在这里插入图片描述

UI编辑

点击编辑,双击mainwindow.ui,进入图形化UI编辑界面,编辑UI,在属性中修改控件的值。
在这里插入图片描述
对按键增加信号槽
在这里插入图片描述

逻辑代码编辑

1.在mainwindow.h中增加变量和头文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H


#include <QMainWindow>
#include <QtNetwork/QUdpSocket>
namespace Ui {
class MainWindow;
}


class MainWindow : public QMainWindow
{
    Q_OBJECT


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


private slots:
    void on_btn_config_clicked();


    void on_btn_clearRx_clicked();


    void on_btn_Send_clicked();


    void on_btn_clearSend_clicked();
    void recv();


private:
    Ui::MainWindow *ui;
    //add
    QUdpSocket udpsocket;
    quint16 port_tx;
    quint16 port_rx;
    QHostAddress Ip_Tx;
    QHostAddress Ip_Rx;
};


#endif // MAINWINDOW_H

2.在udpTest.pro中增加“QT += network”

QT       += core gui
QT      += network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets


TARGET = udpTest
TEMPLATE = app




SOURCES += main.cpp\
        mainwindow.cpp


HEADERS  += mainwindow.h


FORMS    += mainwindow.ui

3.在mainwindow.cpp中增加函数内容。

#include "mainwindow.h"
#include "ui_mainwindow.h"


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


MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::recv()
{
    char data[200]={0};
     while(udpsocket.hasPendingDatagrams()) {
         udpsocket.readDatagram((char*)data, udpsocket.pendingDatagramSize());
     }
    ui->edit_Rx->append(data);
}
void MainWindow::on_btn_config_clicked()
{
  bool ok;
  Ip_Tx = QHostAddress(ui->edit_serverIp->text());
  port_tx = ui->edit_serverPort->text().toInt(&ok);
  port_rx = ui->edit_clientPort->text().toInt(&ok);


  udpsocket.bind(port_rx);
  disconnect(&udpsocket, SIGNAL(readyRead()), this, SLOT(recv()));
  connect(&udpsocket, SIGNAL(readyRead()), this, SLOT(recv()));
}


void MainWindow::on_btn_clearRx_clicked()
{
    ui->edit_Rx->clear();
}


void MainWindow::on_btn_Send_clicked()
{
    QString str = ui->edit_Tx->toPlainText();
    QByteArray data=str.toLatin1();
    udpsocket.writeDatagram(data, data.length(), Ip_Tx, port_tx);
}


void MainWindow::on_btn_clearSend_clicked()
{
    ui->edit_Tx->clear();
}

编译测试

利用UDP工具搭建一个服务器,进行功能测试
在这里插入图片描述

打包发布

打包方法参考: https://www.sindsun.com/article-details-67.html
Enigma Virtual Box工具下载: https://download.csdn.net/download/yu1441/10167178
参考工程:https://download.csdn.net/download/fengweibo112/11656392

猜你喜欢

转载自blog.csdn.net/fengweibo112/article/details/100519466