日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Qt学习(六):UDP通信

發布時間:2025/3/12 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Qt学习(六):UDP通信 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

知識點

  • qt中UDP通信
  • 組播
  • 獲取編輯器內容,發送到套接字
    完整項目github地址:
https://github.com/taw19960426/Qt_study/tree/main/QUdpSocket

結果演示

widget.cpp

#include "widget.h" #include "ui_widget.h" #include <QHostAddress>Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget) {ui->setupUi(this);setWindowTitle("服務端port:8888");udpSocket=new QUdpSocket(this);//綁定//udpSocket->bind(8888);udpSocket->bind(QHostAddress::AnyIPv4, 8888);//加入某個組播//組播地址是D類地址udpSocket->joinMulticastGroup( QHostAddress("224.0.0.2") );//udpSocket->leaveMulticastGroup(); //退出組播//當對方成功發送數據過來//自動觸發 readyRead()connect(udpSocket,&QUdpSocket::readyRead,this,&Widget::delUdp); }Widget::~Widget() {delete ui; }void Widget::delUdp(){//讀取對方發送的內容char buf[1024]={0};QHostAddress ip;//對方地址quint16 port;//對方端口qint64 ans=udpSocket->readDatagram(buf,sizeof(buf),&ip,&port);//讀到了if(ans>0){//格式化 [192.68.2.2:8888]aaaaQString str=QString("[%1:%2] %3").arg(ip.toString()).arg(port).arg(buf);//給編輯區設置內容ui->textEdit->setText(str);} }//發送按鈕 void Widget::on_buttonSend_clicked() {//先獲取對方的IP和端口QString ip=ui->lineEditIP->text();quint16 port=ui->lineEditPort->text().toInt();//獲取編輯區內容QString str=ui->textEdit->toPlainText();//給指定的IP發送數據udpSocket->writeDatagram(str.toUtf8(),QHostAddress(ip),port); }

widget.h

#ifndef WIDGET_H #define WIDGET_H#include <QWidget> #include <QUdpSocket>namespace Ui { class Widget; }class Widget : public QWidget {Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();private slots:void on_buttonSend_clicked();private:Ui::Widget *ui;QUdpSocket *udpSocket;//定義處理的槽函數void delUdp(); };#endif // WIDGET_H

總結

以上是生活随笔為你收集整理的Qt学习(六):UDP通信的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。