QT udp 协议简单实现

1.概要

udp协议简单实现,自己发协议,自己接受

2.代码

2.1 工程文件

QT = core
QT += network

CONFIG += c++17 cmdline

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
        main.cpp \
        myudptest.cpp

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

HEADERS += \
    myudptest.h

2.2 主函数 

#include <QCoreApplication>
#include <QDebug>
#include "myudptest.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qDebug()<<"hello udp";
    MyUdpTest* mudp = new MyUdpTest();
    mudp->write();
    return a.exec();
}

 2.3 头文件

#ifndef MYUDPTEST_H
#define MYUDPTEST_H
//#include <QObject>
#include <QUdpSocket>

class MyUdpTest:public QObject
{
public:
    QUdpSocket *udpSocket;
    MyUdpTest();
    void readPendingDatagrams();
    void write();
};

#endif // MYUDPTEST_H

 2.4 app文件

#include "myudptest.h"

MyUdpTest::MyUdpTest()
{
    udpSocket = new QUdpSocket(this);
    udpSocket->bind(QHostAddress::Any, 5001);

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

void MyUdpTest::readPendingDatagrams(){
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        // 处理接收到的数据
        qDebug() << "Received datagram:" << QString::fromUtf8(datagram) << "from" << sender.toString() << ":" << senderPort;
    }
}

void MyUdpTest::write(){
    QHostAddress receiverAddress("192.168.1.106"); // 目标地址
    quint16 receiverPort = 5001; // 目标端口
    QString data = "Hello, UDP!";
    //QByteArray message = data.toUtf8();
    QByteArray message = "Hello, UDP!";
    udpSocket->writeDatagram(message, receiverAddress, receiverPort);
}

3.运行结果

hello udp
Received datagram: "Hello, UDP!" from "::ffff:192.168.1.106" : 5001 

  • 43
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值