ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

QT实现UDP收发报文 简单示例(client端)

2021-09-21 22:34:52  阅读:107  来源: 互联网

标签:udpClient UDP QT 示例 ip void ui 收发报 UdpClient


一直想写博客但是太懒了。。。根据最近做项目用到的东西就写个UDP吧,希望对大家有所帮助,嗯,其他的以后想起来再写。

主要内容:qt作为客户端实现报文的收发,用定时器实现定时写(心跳包),可断开重新连接。

测试别忘记关掉防火墙。

以下代码是简化过的,仅供参考,如有不当之处,欢迎指正。

下载链接(永久有效,失效请评论):

链接:https://pan.baidu.com/s/1aFmmJdO6s5QcRcSyIZysYA 
提取码:a3nk

clent界面:

 UdpClient.pro

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    udpclient.cpp

HEADERS += \
    udpclient.h

FORMS += \
    udpclient.ui

QT += network

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

udpclient.h

#ifndef UDPCLIENT_H
#define UDPCLIENT_H

#include <QMainWindow>
#include <QUdpSocket>

QT_BEGIN_NAMESPACE
namespace Ui {
    class UdpClient;
}
QT_END_NAMESPACE

class UdpClient : public QMainWindow {
    Q_OBJECT

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

private slots:
    void on_connet_pushButton_clicked();
    void sendData();
    void readData();

    void on_connect_pushButton_clicked();

private:
    Ui::UdpClient *ui;
    QUdpSocket *udpClient;
    QString ip;
    qint64 port;
    qint64 reciveTime;
    qint64 sendTime;
    QTimer *writeTimer;

    static const quint64 RESPONSE_INTERVAL;//write周期
    static const quint64 HEARTBEAT_TIMEOUT;//超时未应答时间

    bool isVaildIp(QString &ip);
    void resetStatues();

    bool btnStatues;
};
#endif // UDPCLIENT_H

 udpclient.cpp

#include "udpclient.h"
#include "ui_udpclient.h"
#include <QTimer>
#include <QMessageBox>

const quint64 UdpClient::RESPONSE_INTERVAL = 5; //s
const quint64 UdpClient::HEARTBEAT_TIMEOUT = 15; //s

UdpClient::UdpClient(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::UdpClient) {
    ui->setupUi(this);
    writeTimer = nullptr;
    ip = "192.168.56.200";
    port = 8888;
    sendTime = 0;
    reciveTime = 0;
    btnStatues = false;
    udpClient = new QUdpSocket(this);
    udpClient->bind(QHostAddress(ip), QUdpSocket::ShareAddress);
    QObject::connect(udpClient, SIGNAL(readyRead()), this, SLOT(readData()));
    writeTimer = new QTimer;
    QObject::connect(writeTimer, SIGNAL(timeout()), this, SLOT(sendData()));
}

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

bool UdpClient::isVaildIp(QString &ip) {
    QHostAddress test;
    if (!test.setAddress(ip)) {
        return false;
    }
    return true;
}

void UdpClient::sendData() {
    quint64 now = time(NULL);
    if ((now - sendTime) > RESPONSE_INTERVAL) {
        udpClient->writeDatagram("{\"order\":\"HELLO\"}", QHostAddress(ip), port);
        ui->send_lable->setText("HELLO");
#ifdef QT_DEBUG
        qDebug() << "send: HELLO";
#endif
        sendTime = now;
    }
}

void UdpClient::readData() {
    QByteArray arr;
    quint64 now = time(NULL);
    while(udpClient->hasPendingDatagrams()) {
        arr.resize(udpClient->bytesAvailable());
        udpClient->readDatagram(arr.data(), arr.size());
        reciveTime = now;
#ifdef QT_DEBUG
        qDebug() << "read: " << arr.data();
#endif
    }
    if (!strcmp(arr.data(), "HELLO")) {
        ui->connect_pushButton->setText("断开");
        btnStatues = true;
        ui->recive_lable->setText(arr.data());
    }  else {
        if(now - reciveTime > HEARTBEAT_TIMEOUT) {
            ui->connect_pushButton->setText("连接");
            btnStatues = false;
        }
    }
}

void UdpClient::resetStatues() {
    sendTime = 0;
    reciveTime = 0;
}

void UdpClient::on_connect_pushButton_clicked() {
    if(!btnStatues) { //未连接
        if(!isVaildIp(ip)) {
            QMessageBox::warning(NULL, "提示", "IP地址不合法!", QMessageBox::Ok);
            return;
        }
    } else {
        udpClient->close();//必须关闭,不然无法重新绑定
        resetStatues();
        btnStatues = false;
        writeTimer->stop();
        ui->connect_pushButton->setText("连接");
        return;
    }
#ifdef QT_DEBUG
    qDebug() << "connecting: " << ip << " port: " << port;
#endif
    udpClient->bind(QHostAddress(ip), QUdpSocket::ShareAddress);
    writeTimer->start(0);
}

标签:udpClient,UDP,QT,示例,ip,void,ui,收发报,UdpClient
来源: https://blog.csdn.net/qq_32162235/article/details/120405452

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有