Qt文档阅读笔记-Broadcast Receiver Example解析
Posted IT1995
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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_NAMESPACE
class Receiver : public QWidget
{
Q_OBJECT
public:
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解析的主要内容,如果未能解决你的问题,请参考以下文章
Qt文档阅读笔记-Simple Chat Example解析
Qt文档阅读笔记-QNetworkProxy::ProxyType解析(Qt设置Fiddler代理)