当前位置:   article > 正文

QT udp 协议简单实现

QT udp 协议简单实现

1.概要

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

2.代码

2.1 工程文件

  1. QT = core
  2. QT += network
  3. CONFIG += c++17 cmdline
  4. # You can make your code fail to compile if it uses deprecated APIs.
  5. # In order to do so, uncomment the following line.
  6. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
  7. SOURCES += \
  8. main.cpp \
  9. myudptest.cpp
  10. # Default rules for deployment.
  11. qnx: target.path = /tmp/$${TARGET}/bin
  12. else: unix:!android: target.path = /opt/$${TARGET}/bin
  13. !isEmpty(target.path): INSTALLS += target
  14. HEADERS += \
  15. myudptest.h

2.2 主函数 

  1. #include <QCoreApplication>
  2. #include <QDebug>
  3. #include "myudptest.h"
  4. int main(int argc, char *argv[])
  5. {
  6. QCoreApplication a(argc, argv);
  7. qDebug()<<"hello udp";
  8. MyUdpTest* mudp = new MyUdpTest();
  9. mudp->write();
  10. return a.exec();
  11. }

 2.3 头文件

  1. #ifndef MYUDPTEST_H
  2. #define MYUDPTEST_H
  3. //#include <QObject>
  4. #include <QUdpSocket>
  5. class MyUdpTest:public QObject
  6. {
  7. public:
  8. QUdpSocket *udpSocket;
  9. MyUdpTest();
  10. void readPendingDatagrams();
  11. void write();
  12. };
  13. #endif // MYUDPTEST_H

 2.4 app文件

  1. #include "myudptest.h"
  2. MyUdpTest::MyUdpTest()
  3. {
  4. udpSocket = new QUdpSocket(this);
  5. udpSocket->bind(QHostAddress::Any, 5001);
  6. connect(udpSocket, &QUdpSocket::readyRead, this, &MyUdpTest::readPendingDatagrams);
  7. }
  8. void MyUdpTest::readPendingDatagrams(){
  9. while (udpSocket->hasPendingDatagrams()) {
  10. QByteArray datagram;
  11. datagram.resize(udpSocket->pendingDatagramSize());
  12. QHostAddress sender;
  13. quint16 senderPort;
  14. udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
  15. // 处理接收到的数据
  16. qDebug() << "Received datagram:" << QString::fromUtf8(datagram) << "from" << sender.toString() << ":" << senderPort;
  17. }
  18. }
  19. void MyUdpTest::write(){
  20. QHostAddress receiverAddress("192.168.1.106"); // 目标地址
  21. quint16 receiverPort = 5001; // 目标端口
  22. QString data = "Hello, UDP!";
  23. //QByteArray message = data.toUtf8();
  24. QByteArray message = "Hello, UDP!";
  25. udpSocket->writeDatagram(message, receiverAddress, receiverPort);
  26. }

3.运行结果

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/795386
推荐阅读
相关标签
  

闽ICP备14008679号