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

    }
}

运行结果如下:

相关推荐
谱写秋天4 小时前
Qt 5.5 的安装与配置(使用 VSCode编辑)
开发语言·vscode·qt
前端市界19 小时前
前端视角: PyQt6+Vue3 跨界开发实战
前端·qt·pyqt
誰能久伴不乏1 天前
Qt 动态属性(Dynamic Property)详解
开发语言·qt
枫叶丹41 天前
【Qt开发】常用控件(四)
开发语言·qt
茉莉玫瑰花茶2 天前
Qt 常用控件 - 9
开发语言·qt
sqmeeting2 天前
QT6 如何在Linux Wayland 桌面系统抓屏和分享屏幕
linux·qt
姓刘的哦2 天前
Win10上Qt使用Libcurl库
开发语言·qt
hellokandy3 天前
QT QVersionNumber 比较版本号大小
qt·版本号·qversionnumber
常乐か3 天前
VS2022+QT5.15.2+OCCT7.9.1的开发环境搭建流程
开发语言·qt·opencascade
誰能久伴不乏3 天前
Qt TCP 客户端对象生命周期与连接断开问题解析
网络·qt·tcp/ip