UDP 協議是開放式,無連接,不可靠的傳輸層通信協議,但它收發數據的速度相對于 TCP 快很多,常用在傳輸音視頻等數據量非常大的場合。
udp 網絡編程只需要使用一個類 QUdpSocket。
本實驗中對 QUdpSocket 的基本使用:
1.創建 QUdpSocket 對象。
2.綁定端口號
3.數據到來觸發 readyRead()信號。
4.讀取發送數據。
5.關閉。
具體步驟:
步驟一:組裝 ui 界面,和 TCP 章節搭建 UI 界面方法一致。
步驟二:編寫代碼
1.創建 QUdpSocket 對象,使用 bind 函數綁定端口號和套接字,數據報到來后會發出信 號
(),在綁定的槽函數內去讀取數據。
2.讀取數據,數據到來 hasPendingDatagrams()返回 true,再用 pendingDatagramSize()獲取數據報的長度,如果數據沒有被讀取
完,hasPendingDatagrams()就會返回 true,直至數據都被讀取完。
readDatagram(data,size);
參數 data 為讀取的數據,size 為數據長度。
3.發送數據,使用 writeDatagram 函數,
writeDatagram(const char *data, qint64 len, const QHostAddress &host, quint16 port);
Data:發送的數據。
Len:發送的數據長度。
Host:目標 IP 地址。
Port:目標端口號。
4.關閉 socket 套接字。
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
udp.h
#include #include namespace Ui { class Udp; } class Udp : public QMainWindow { Q_OBJECT public: explicit Udp(QWidget *parent = 0); ~Udp(); QUdpSocket * udpSocket; private slots: void on_pushButton_clicked(); void readyRead_Slot(void); void on_pushButton_3_clicked(); void on_pushButton_2_clicked(); private: Ui::Udp *ui; }; udp.cpp: Udp::Udp(QWidget *parent) : QMainWindow(parent), ui(new Ui::Udp) { ui->setupUi(this); udpSocket = new QUdpSocket(this); } Udp::~Udp() { delete ui; } /* * 打開按鈕 */ void Udp::on_pushButton_clicked() { //綁定本端口的端口號 if(udpSocket->bind(ui->cliEdit->text().toUInt()) == true){ QMessageBox::information(this,'提示','成功'); }else{ QMessageBox::information(this,'提示','失敗'); } //綁定數據信號和槽函數 connect(udpSocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot())); } /* *讀取數據槽函數 */ void Udp::readyRead_Slot() { QString buf; QByteArray array; //hasPendingDatagrams()返回 true 時表示至少有一個數據報在等待被讀取 while(udpSocket->hasPendingDatagrams()){ //獲取數據 array.resize(udpSocket->pendingDatagramSize()); udpSocket->readDatagram(array.data(),array.size()); buf = array.data(); ui->recvEdit->appendPlainText(buf); } } /* * 發送數據 */ void Udp::on_pushButton_3_clicked() { quint16 port; QString sendBuff; QHostAddress address; address.setAddress(ui->ipEdit->text());//目標機地址 port = ui->portEdit->text().toInt();//目標機端口號 sendBuff = ui->sendEdit->text();//發送的數據 //發送 udpSocket->writeDatagram(sendBuff.toLocal8Bit().data(),sendBuff.length(),address,port); } /* *關閉 */ void Udp::on_pushButton_2_clicked() { udpSocket->close(); }
上一篇:迅為IMX6Q開發板AndroidStudio-calendar測試
下一篇:4412開發板Qt定時器-實驗步驟和部分代碼
推薦閱讀最新更新時間:2025-04-12 07:21





設計資源 培訓 開發板 精華推薦
- DC794A,用于 LT6554CGN 三路高速視頻緩沖器(3.3V 至 5V 和 -3.3V 至 -5V)的演示板
- ADA4000-2ARZ-RL運算放大器緩沖網絡配置的典型應用電路
- 使用 ROHM Semiconductor 的 BD60GA5WEFJ 的參考設計
- 使用 Infineon Technologies AG 的 TDA 16847-2 的參考設計
- [失敗]CM1033保護板
- 2.4G自制手柄2.0
- 使用 Microchip Technology 的 TC2574 的參考設計
- AD9115-DPG2-EBZ,使用 AD9115 雙路低功耗、10 位 TxDAC 數模轉換器的評估板
- 1.45V、6 芯、鎳鎘便攜式電池充電器
- 帶直流音量控制的5W+5W功放的典型應用