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

    }
}

运行结果如下:

相关推荐
秋田君3 小时前
QT_QT布局详解
开发语言·数据库·qt
辞旧 lekkk4 小时前
【Qt系统相关】鼠标事件
linux·开发语言·qt·学习·计算机外设·萌新
贺国亚10 小时前
A2A协议与Agent互操作-Task生命周期
开发语言·qt
luoyayun36119 小时前
Qt + FFmpeg 视频工具:视频一键压缩功能实现
qt·ffmpeg·音视频·视频压缩
blueman888819 小时前
Qt5通过vcpkg中调用时,在debug模式下调试时总是调用release的plugins文件夹中的dll
c++·qt·cmake
南国韭菜1 天前
【无标题】
c++·qt
旋律翼21 天前
Qt Bridges for C# 深度技术解析
开发语言·qt·c#
郝学胜-神的一滴1 天前
Qt 高级编程 035:无边框窗口+自定义标题栏 完整实现详解
开发语言·c++·qt·程序人生·用户界面
辞旧 lekkk1 天前
CMake工程指南(一)
linux·运维·服务器·开发语言·qt·学习·萌新
blueman88882 天前
qt5-serialbus详细解析
开发语言·网络·qt