linux下的udp 通信過程:
Qt下的UDP 通信過程:
組播地址分類(組播地址一定要用D類):
工程目錄:
Udp.pro:
#------------------------------------------------- # # Project created by QtCreator 2019-07-08T09:05:20 # #------------------------------------------------- QT += core gui network greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = Udp TEMPLATE = app SOURCES += main.cpp\ widget.cpp HEADERS += widget.h FORMS += widget.ui
widget.h:
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QUdpSocket>//UDP套接字 namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); //之前用的都是lambda表達式,這次就用自定義的槽函數,來溫習以下以前所學的內容; void dealMsg();//槽函數,處理對方發過來的數據(槽函數的形式與信號保持一致,沒有參數) private slots: void on_buttonSend_clicked(); private: Ui::Widget *ui; QUdpSocket *udpSocket;//UDP套接字 }; #endif // WIDGET_H
widget.cpp:
#include "widget.h" #include "ui_widget.h" #include <QHostAddress> Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); //分配空間,指定父對象 udpSocket = new QUdpSocket(this); //綁定 udpSocket->bind(8888); //組播的綁定 /*udpSocket->bind(QHostAddress::AnyIPv4,8888); */ /*總是廣播的話,容易造成網絡擁堵,造成丟包的現象較多,所以出現了組播(類似建立qq群) * 加入某個組播 * 組播地址是D類地址 * 事實上這么寫udpSocket->joinMulticastGroup(QHostAddress("224.0.0.2")); * 依然不對的,會出現cannot bind to QHostAddress::Any 這樣一句話,這是因為電腦上本身既有Ipv4又有ipv6, * 此時就不能使用udpSocket->bind(8888);進行綁定,這樣綁定是綁定任何的ip。 * 而應該使用udpSocket->bind(QHostAddress::AnyIPv4,8888); * */ udpSocket->joinMulticastGroup(QHostAddress("224.0.0.2")); // udpSocket->leaveMulticastGroup(QHostAddress("224.0.0.2"));//退出組播 setWindowTitle("服務器端口:8888"); //當對方成功發送數據過來 //自動觸發readyRead() //之前用的都是lambda表達式,這次就用自定義的槽函數,來溫習以下以前所學的內容; connect(udpSocket,&QUdpSocket::readyRead,this,&Widget::dealMsg); } void Widget::dealMsg() { //讀取對方發送的內容 char buf[1024] = {0}; QHostAddress cliAddr;//對方地址 quint16 port;//對方端口號 qint64 len = udpSocket->readDatagram(buf,sizeof(buf),&cliAddr,&port); if (len > 0) { //格式化 輸出的形式如:[111.111.111.111:8888] aaaa QString str = QString("[%1 : %2] %3").arg(cliAddr.toString()).arg(port).arg(buf); //給編輯區設置內容 ui->textEdit->setText(str); } } Widget::~Widget() { delete ui; } //發送按鈕(轉到槽) void Widget::on_buttonSend_clicked() { //先獲取對方的IP和端口 QString ip = ui ->lineEditIp->text(); qint16 port = ui->lineEditPort->text().toInt(); //獲取編輯區內容 QString str = ui->textEdit->toPlainText(); //給指定的IP發送數據 udpSocket->writeDatagram(str.toUtf8(),QHostAddress(ip),port); }
ui: