Qt学习(六):UDP通信
生活随笔
收集整理的這篇文章主要介紹了
Qt学习(六):UDP通信
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
知識點
- qt中UDP通信
- 組播
- 獲取編輯器內容,發送到套接字
完整項目github地址:
結果演示
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通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt学习(五):TCP通信
- 下一篇: Qt学习(七):定时器QTimer