Qt文档阅读笔记-Broadcast Receiver Example解析
生活随笔
收集整理的這篇文章主要介紹了
Qt文档阅读笔记-Broadcast Receiver Example解析
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
這篇博文的例子是說明如何在局域網(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)鍵代碼:
解釋:廣播報使用的是UDP,所以用的是QUdpSocket,并且綁定了端口45454。
?
解釋:關(guān)聯(lián)了信號與槽當網(wǎng)卡緩存中有數(shù)據(jù)時,調(diào)用對應(yīng)的槽函數(shù)進行讀取。
?解釋:當緩存區(qū)有數(shù)據(jù)時:hasPendingDatagrams(),然后就使用QByteArray獲取讀到的數(shù)據(jù),最后設(shè)置到label上。
?
總結(jié)
以上是生活随笔為你收集整理的Qt文档阅读笔记-Broadcast Receiver Example解析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux笔记-Centos7.6安装Q
- 下一篇: Arduino笔记-人体感应灯项目