1.IDE:QTCreator
2.实验:UDP
不分客户端和服务端
3.记录
(1)做一个UI界面
(2)编写open按钮代码进行测试(用网络调试助手测试)
(3)完善其他功能测试
4.代码
pro
QT += core gui networkgreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsCONFIG += c++17# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0SOURCES += \main.cpp \widget.cppHEADERS += \widget.hFORMS += \widget.ui# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QUdpSocket> //
#include <QString> //
#include <QHostAddress>
QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTQUdpSocket *udpsocket; //
public:Widget(QWidget *parent = nullptr);~Widget();private slots:void on_open_pb_clicked();void readyRead_slot();void on_close_pb_clicked();void on_send_pb_clicked();private:Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox> //
Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);udpsocket = new QUdpSocket(this); //
}Widget::~Widget()
{delete ui;
}void Widget::on_open_pb_clicked() //打开按钮按下处理函数
{if(udpsocket->bind(ui->local_port->text().toUInt())==true) //连接成功{QMessageBox::information(this,"提示","连接成功");}else{QMessageBox::critical(this,"警告","连接失败");}connect(udpsocket,SIGNAL(readyRead()),this,SLOT(readyRead_slot()));
}void Widget::readyRead_slot() //准备读关联函数
{while (udpsocket->hasPendingDatagrams()) {QByteArray array;array.resize(udpsocket->pendingDatagramSize());udpsocket->readDatagram(array.data(),array.size());QString buf;buf=array.data();ui->receive_line->appendPlainText(buf);}
}void Widget::on_close_pb_clicked() //关闭按钮按下时
{udpsocket->close();
}void Widget::on_send_pb_clicked() //发送按钮按下时
{quint16 port;QString sendbuff;QHostAddress address;address.setAddress(ui->des_ip->text()); //设置目标IPsendbuff=ui->send_line->text(); //发送内容存入数组port=ui->des_port->text().toUInt(); //目标端口赋值udpsocket->writeDatagram(sendbuff.toLocal8Bit().data(),sendbuff.length(),address,port); //udp向指定的IP地址的指定端口发送数据
}