日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2025/3/15 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Qt文档阅读笔记-Broadcast Receiver Example解析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

這篇博文的例子是說明如何在局域網上搭建廣播包接收端。

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

結構如下:

代碼如下:

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] }

解釋關鍵代碼:

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

?

解釋:關聯了信號與槽當網卡緩存中有數據時,調用對應的槽函數進行讀取。

?解釋:當緩存區有數據時:hasPendingDatagrams(),然后就使用QByteArray獲取讀到的數據,最后設置到label上。

?

總結

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

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