介绍:

  1. UDP协议是一种不可靠的网络协议,它在通信的两端各建立一个Socket对象,但是这两个Socket只是发送,接收数据的对象,因此对于基于UDP协议的通信双方而言,没有所谓的客户端和服务器的概念
  2. QT中提供了QUdpSocket类实现UDP通信

特点:

  1. UDP是无连接通信协议,即在数据传输时,数据的发送端和接收端不建立逻辑连接
  2. 消耗系统资源小,通信效率高

模型:

                              

代码实现步骤:

  1. 创建QUdpSocket类
  2. 绑定本端设备IP端口
  3. 构造接收槽函数
  4. 连接接收数据信号和槽函数

工程源码实现如下:

需要在.pro文件下调用以下语句:

QT += network

 xxxx.h文件实现:

 1 #ifndef UDPRECEIVER_H
 2 #define UDPRECEIVER_H
 3 
 4 #include <QObject>
 5 #include <QUdpSocket>
 6 
 7 class UdpReceiver : public QObject
 8 {
 9     Q_OBJECT
10 
11 public:
12     UdpReceiver(QObject *p = 0);
13     ~UdpReceiver();
14 
15 public slots:
16     void receive();
17 
18 private:
19     QUdpSocket *uSocket;
20 };
21 
22 #endif // UDPRECEIVER_H

xxx.cpp文件实现如下:

 1 #include <QByteArray>
 2 #include <iostream>
 3 #include "UdpReceiver.h"
 4 #include <QDebug>
 5 #include <QString>
 6 #include <QFile>
 7 
 8 //const quint16 PORT = 2333;//const修饰符表明参数只能读取,不能修改
 9 quint16 PORT = 2333;
10 
11 UdpReceiver::UdpReceiver(QObject *p) :
12     QObject(p)
13 {
14     //打开txt配置文件,获取IP和Port
15     QFile file("./test.txt");
16     if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
17     {
18 
19     }
20     QString line=file.readLine();
21     QString getIP;
22     QString getPort;
23     while(!line.isEmpty())
24     {
25 
26         if(line.contains("ipAddress"))
27         {
28             getIP = line.mid(10);//取出文件中的IP
29             getIP = getIP.trimmed();//删除当前字符串中的换行符
30         }
31 
32         if(line.contains("ipPort"))
33         {
34             getPort = line.mid(7);//取出文件中的Port
35             getPort = getPort.trimmed();//删除当前字符串中的换行符
36         }
37         line=file.readLine();
38     }
39     file.close();//获取到IP和Port之后关闭文件
40     printf("ip:%s   port:%s\n",getIP.toStdString().data(),getPort.toStdString().data());
41 
42     PORT = quint16(getPort.toUInt());
43 
44     uSocket = new QUdpSocket;
45     uSocket->bind(QHostAddress(getIP), PORT);
46     connect(uSocket, SIGNAL(readyRead()), this, SLOT(receive()));
47 }
48 
49 UdpReceiver::~UdpReceiver()
50 {
51     delete uSocket;
52 }
53 
54 void UdpReceiver::receive()
55 {
56     QByteArray ba;
57     QHostAddress clientAddr;
58     quint16 clientPort;
59     while(uSocket->hasPendingDatagrams())
60     {
61         ba.resize(uSocket->pendingDatagramSize());
62         uSocket->readDatagram(ba.data(), ba.size(),&clientAddr,&clientPort);//接收数据报
63 
64         printf("length:%d",ba.length());
65         printf("\n");
66 
67         printf("data:%s",ba.data());
68         printf("\n");
69 
70         qDebug()<<clientAddr;
71         printf("clientPort=%d\n",clientPort);
72 
73         for(int i = 0;i<ba.length();i++)
74         {
75             printf("0x%02hhx ",ba.data()[i]);
76         }
77         printf("\n");
78 
79     }
80     printf("out");
81 }

View Code

编译好以上代码后,可以使用网络调试助手进行调试验证,调试可参考以下操作:

 

 工程源码下载:

链接:https://pan.baidu.com/s/1i2vM3Uf3GAVmdCqf_FuETA
提取码:govd