迅為4412開發板Qt網絡編程-UDP實現服務器和客戶端
發布時間:2021-5-13 09:39
發布者:
落風
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 套接字。
代碼如下:
- 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();
- }
復制代碼
步驟三:運行測試,收發功能正常如圖:
|