Qt中对Udp数据打包发送和接收

news/2024/5/18 15:59:56 标签: udp, 网络协议, 网络

有些小伙伴对怎么对Udp的数据打包不太清楚。下面我举例说明。

比如我们要发送一个Person的数据。可以先用一个结构把Person的数据封装。

struct Person {
    QString name;
    int age;
};

下面是udp客户端和服务器端完整的代码例子。


#ifndef UDPCLIENT_H
#define UDPCLIENT_H

#include <QObject>
#include <QUdpSocket>

struct Person {
    QString name;
    int age;
};

class UdpClient : public QObject
{
    Q_OBJECT
public:


    explicit UdpClient(QObject *parent = nullptr);
    void sendDatagram(const QByteArray &data);

private slots:
    void readPendingDatagrams();

private:
    void processDatagram(const QNetworkDatagram &datagram);
    QUdpSocket *udpSocket;
};

#endif // UDPCLIENT_H
        

#include "UdpClient.h"
#include <QDataStream>
#include <QNetworkDatagram>

UdpClient::UdpClient(QObject *parent) : QObject(parent) {
    udpSocket = new QUdpSocket(this);
    udpSocket->bind(QHostAddress::LocalHost, 1235);

    connect(udpSocket, &QUdpSocket::readyRead, this, &UdpClient::readPendingDatagrams);
}

void UdpClient::sendDatagram(const QByteArray &data) {
    udpSocket->writeDatagram(data, QHostAddress::LocalHost, 1234);
}

void UdpClient::readPendingDatagrams() {
    while (udpSocket->hasPendingDatagrams()) {
        QNetworkDatagram datagram = udpSocket->receiveDatagram();
        processDatagram(datagram);
    }
}

void UdpClient::processDatagram(const QNetworkDatagram &datagram) {
    QByteArray data = datagram.data();
    // Here you would process the data
    QDataStream stream(data);
   Person person;
   stream >> person.name >> person.age;

   // 现在你可以使用 person 结构中的数据
   qDebug() << "Received person: " << person.name << ", " << person.age;
}
        

#ifndef UDPSERVER_H
#define UDPSERVER_H

#include <QObject>
#include <QUdpSocket>

class UdpServer : public QObject
{
    Q_OBJECT
public:
    explicit UdpServer(QObject *parent = nullptr);

private slots:
    void readPendingDatagrams();

private:
    void processDatagram(const QNetworkDatagram &datagram);
    QUdpSocket *udpSocket;
};

#endif // UDPSERVER_H

#include "UdpServer.h"

#include <QNetworkDatagram>

UdpServer::UdpServer(QObject *parent) : QObject(parent) {
    udpSocket = new QUdpSocket(this);
    udpSocket->bind(QHostAddress::LocalHost, 1234);

    connect(udpSocket, &QUdpSocket::readyRead, this, &UdpServer::readPendingDatagrams);
}

void UdpServer::readPendingDatagrams() {
    while (udpSocket->hasPendingDatagrams()) {
        QNetworkDatagram datagram = udpSocket->receiveDatagram();
        processDatagram(datagram);
    }
}

void UdpServer::processDatagram(const QNetworkDatagram &datagram) {
    QByteArray data = datagram.data();
    // Here you would process the data
    // ...
    //qDebug() << "Received data from client: " << data.toStdString().c_str();

    // Sending a response back to the sender
    udpSocket->writeDatagram(data, datagram.senderAddress(), datagram.senderPort());
}
        

#include <QCoreApplication>
#include <QDataStream>
#include "UdpServer.h"
#include "UdpClient.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    UdpServer server;
    UdpClient client;

    Person person;
    person.name = "Alice";
    person.age = 30;

    QByteArray datagram;
    QDataStream stream(&datagram, QIODevice::WriteOnly);
    stream << person.name << person.age;

    client.sendDatagram(datagram);

    return a.exec();
}
        
        


http://www.niftyadmin.cn/n/5169345.html

相关文章

电大搜题:开启智能学习新时代

尊敬的读者朋友们&#xff0c;今天我将向您介绍一款能够让您轻松搜题、高效学习的神奇工具&#xff1a;电大搜题&#xff01;作为湖北开放大学和广播电视大学的学习者&#xff0c;您一定对于繁重的课业和复杂的试题感到头疼。但是&#xff0c;现在有了电大搜题微信公众号&#…

SIMULIA--Abaqus结构仿真篇

什么是 SIMULIA? 基于3DEXPERIENCE平台的品牌 多学科多领域的协同仿真与分析优化 三大核心仿真领域&#xff1a;电磁仿真 流体仿真 结构仿真 SIMULIA结构仿真是什么? 对结构进行力学、热学、声学等多学科计算&#xff0c;辅助于设计方案优化.采用数字化技术模拟产品性能&am…

ubuntu 16.04.5 安装 vivado 2019.1 完整编译AD9361的环境

一、前期安装 1、安装ncurses库&#xff08;已经包含了&#xff0c;其他的os需要安装&#xff09; sudo apt install libncurses5二、安装 sudo ./xsetup使用lic进行激活。 三、安装后 输入指令 sudo gedit ~/.bashrc 末尾添加 source /opt/Xilinx/Vivado/2019.1/setti…

Open3D 使用自定义多边形numpy数组边界裁剪点云( 附python 代码)多边形内部点

首先创建了一个包含多个多边形边界点的numpy 坐标数组。 然后,我们定义了一个多边形选择体积的顶点坐标数组 vertices,用于创建 SelectionPolygonVolume 对象 selection_volume。我们设置了 orthogonal_axis 为 "Z",表示选择体积的法向轴为 Z 轴;并设置了 bound…

亚数受邀参加第六届进博会配套论坛,获评“2023年度上海重点产业提升国际竞争力示范案例”!

11月8日&#xff0c;由上海市商务委指导&#xff0c;上海社科院和临港集团主办&#xff0c;上海社科院应用经济研究所、徐汇虹梅街道和上海市漕河泾新兴技术开发区开发总公司联合承办&#xff0c;长三角产业国际竞争力联盟协办的第六届中国国际进口博览会提升上海产业国际竞争力…

xcorr函数的用法和程序举例

xcorr函数的用法和程序举例 xcorr函数返回两个离散时间序列的互相关。互相关测量向量 x 和移位&#xff08;滞后&#xff09;副本向量y 的之间的相似性&#xff0c;形式为滞后的函数。如果 x 和 y 的长度不同&#xff0c;函数会在较短向量的末尾添加零&#xff0c;使其长度与另…

nginx请求静态资源POST 405 Not Allowed问题

今天部署一个前端程序, 访问时提示错误: 405 Not Allowed, 我的情况是用ajax请求json数据, 数据存在一个json文件中, 请求是报这个错误, 我的解决方式如下: location / {root /usr/share/nginx/html8085;try_files $uri $uri/ /index.html;index index.html index.htm;error…

使用电脑上自带的软件进行远程连接

使用电脑上自带的软件进行远程连接 首先需要让你远程的电脑设置成允许远程连接 Windows R打开运行面板&#xff0c;然后输入sysdm.cpl命令&#xff0c;如下图&#xff1a; 选择“远程”选项卡&#xff0c;确保选中“允许远程连接到这台计算机”&#xff0c;如下图&#xff1…