QT upd测试

QT upd测试

本次测试将服务器和客户端写在了一个工程下,代码如下

widget.h

cpp 复制代码
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include<QUdpSocket>
#include<QTimer>

QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

private slots:
    void on_pushButton_clicked();

    void dataReceived();

    void on_pushButton_2_clicked();
    void timeoutslot();

private:
    Ui::Widget *ui;

public:
    int m_iport;
    bool m_bisstarted;
    QUdpSocket *udpSocket_server;
     QUdpSocket *udpSocket_client;
    QTimer *timer;
};
#endif // WIDGET_H

widget.cpp

cpp 复制代码
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    m_iport = 5555;
    udpSocket_server = new QUdpSocket(this);
    udpSocket_client = new QUdpSocket(this);
    udpSocket_client->bind(m_iport);
    timer = new QTimer(this);
    connect(timer , SIGNAL(timeout()) , this , SLOT(timeoutslot()));
    connect(udpSocket_client , SIGNAL(readyRead()) , this , SLOT(dataReceived()));
    this->setWindowTitle("updtest");

}

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

void Widget::on_pushButton_clicked()
{
    timer->start(500);
}

void Widget::timeoutslot()
{
    QString msg = ui->lineEdit_send->text();
    if(msg.size()==0)
    {
        return;
    }
    //转成utf8 避免中文乱码
    udpSocket_server->writeDatagram(msg.toUtf8 ().data(), msg.toUtf8().size() , QHostAddress::Broadcast , m_iport);

}


void Widget::on_pushButton_2_clicked()
{
    close();
}


void Widget::dataReceived()
{
    while(udpSocket_client->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket_client->pendingDatagramSize());
        udpSocket_client->readDatagram(datagram.data() , datagram.size());
        QString msg = datagram.data();
        ui->textEdit->insertPlainText(msg);

    }
}

运行结果如下:

相关推荐
uyeonashi13 小时前
【QT系统相关】QT文件
开发语言·c++·qt·学习
Wyn_17 小时前
【QT】QTableView自定义样式:仅显示行间隔、隐藏列间隔、表头样式、表格样式、单行选中等
qt·qtableview
٩( 'ω' )و26019 小时前
qt信号与槽--01
开发语言·qt
傻傻虎虎20 小时前
【QT】自动更新库QSimpleUpdater使用实例封装
开发语言·qt
道剑剑非道1 天前
QT开发技术【ffmpeg EVideo录屏软件 一】
开发语言·qt·ffmpeg
H2122021651 天前
P5 QT项目----会学网络调试助手服务端(5.1)
开发语言·网络·qt
委婉待续1 天前
Qt的学习(三)
开发语言·qt·学习
笨笨马甲1 天前
扩展模块--QWebEngine功能及架构解析
qt·架构
yxc_inspire1 天前
基于Qt的app开发第十四天
前端·c++·qt·app·面向对象·qss
Cai junhao1 天前
【Qt】工具介绍和信号与槽机制
开发语言·c++·qt·qt6.3