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

    }
}

运行结果如下:

相关推荐
ShineWinsu1 天前
对于Qt:信号量(QSemaphore)的解析
c++·qt·面试·笔试·客户端·线程安全·信号量
ShineWinsu2 天前
对于Qt:条件变量(QWaitCondition)的解析
c++·qt·面试·线程·条件变量·客户端·锁
郝学胜-神的一滴3 天前
Effective STL 条款12:对容器线程安全性的现实期望
c语言·开发语言·c++·qt·网络协议·rpc·numpy
敲上瘾3 天前
Qt 常用控件:按钮、显示输入、容器与布局等
开发语言·c++·qt·qt6.3
ShineWinsu4 天前
对于Qt:事件分发器以及事件过滤器的解析
c++·qt·面试·gui·客户端·事件过滤器·事件分发器
ShineWinsu4 天前
对于Qt:事件的解析
c++·qt·面试·笔试·gui·客户端·事件
西西弗Sisyphus5 天前
Qt QML 程序是怎么跑起来的(1)qml-only
开发语言·c++·qt
小灰灰搞电子5 天前
QAccel 类讲解与代码示例:Qt 3 中的键盘加速键管理
qt·计算机外设
ShineWinsu6 天前
对于Qt:重写事件步骤的解析
开发语言·c++·qt·客户端·事件·鼠标事件·步骤
敲上瘾7 天前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui