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

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

Qt文档阅读笔记-Broadcast Receiver Example解析

發(fā)布時(shí)間:2025/3/15 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Qt文档阅读笔记-Broadcast Receiver Example解析 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

這篇博文的例子是說(shuō)明如何在局域網(wǎng)上搭建廣播包接收端。

這里使用了Qt Network API,搭建本地廣播包接收端。

結(jié)構(gòu)如下:

代碼如下:

receiver.h

#ifndef RECEIVER_H #define RECEIVER_H#include <QWidget>QT_BEGIN_NAMESPACE class QLabel; class QUdpSocket; QT_END_NAMESPACEclass Receiver : public QWidget {Q_OBJECTpublic:explicit Receiver(QWidget *parent = nullptr);private slots:void processPendingDatagrams();private:QLabel *statusLabel = nullptr;QUdpSocket *udpSocket = nullptr; };#endif

?main.cpp

#include <QApplication>#include "receiver.h"int main(int argc, char *argv[]) {QApplication app(argc, argv);Receiver receiver;receiver.show();return app.exec(); }

?receiver.cpp

#include <QtWidgets> #include <QtNetwork>#include "receiver.h"Receiver::Receiver(QWidget *parent): QWidget(parent) {statusLabel = new QLabel(tr("Listening for broadcasted messages"));statusLabel->setWordWrap(true);auto quitButton = new QPushButton(tr("&Quit"));//! [0]udpSocket = new QUdpSocket(this);udpSocket->bind(45454, QUdpSocket::ShareAddress); //! [0]//! [1]connect(udpSocket, SIGNAL(readyRead()),this, SLOT(processPendingDatagrams())); //! [1]connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));auto buttonLayout = new QHBoxLayout;buttonLayout->addStretch(1);buttonLayout->addWidget(quitButton);buttonLayout->addStretch(1);auto mainLayout = new QVBoxLayout;mainLayout->addWidget(statusLabel);mainLayout->addLayout(buttonLayout);setLayout(mainLayout);setWindowTitle(tr("Broadcast Receiver")); }void Receiver::processPendingDatagrams() {QByteArray datagram; //! [2]while (udpSocket->hasPendingDatagrams()) {datagram.resize(int(udpSocket->pendingDatagramSize()));udpSocket->readDatagram(datagram.data(), datagram.size());statusLabel->setText(tr("Received datagram: \"%1\"").arg(datagram.constData()));} //! [2] }

解釋關(guān)鍵代碼:

解釋:廣播報(bào)使用的是UDP,所以用的是QUdpSocket,并且綁定了端口45454。

?

解釋:關(guān)聯(lián)了信號(hào)與槽當(dāng)網(wǎng)卡緩存中有數(shù)據(jù)時(shí),調(diào)用對(duì)應(yīng)的槽函數(shù)進(jìn)行讀取。

?解釋:當(dāng)緩存區(qū)有數(shù)據(jù)時(shí):hasPendingDatagrams(),然后就使用QByteArray獲取讀到的數(shù)據(jù),最后設(shè)置到label上。

?

總結(jié)

以上是生活随笔為你收集整理的Qt文档阅读笔记-Broadcast Receiver Example解析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。