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

Posted IT1995

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Qt文档阅读笔记-Broadcast Sender Example解析相关的知识,希望对你有一定的参考价值。

此例子展示了使用Qt Network API发送广播包

程序结构如下:

代码如下:

sender.h

#ifndef SENDER_H
#define SENDER_H

#include <QWidget>
#include <QTimer>

QT_BEGIN_NAMESPACE
class QLabel;
class QPushButton;
class QUdpSocket;
QT_END_NAMESPACE

class Sender : public QWidget
{
    Q_OBJECT

public:
    explicit Sender(QWidget *parent = nullptr);

private slots:
    void startBroadcasting();
    void broadcastDatagram();

private:
    QLabel *statusLabel = nullptr;
    QPushButton *startButton = nullptr;
    QUdpSocket *udpSocket = nullptr;
    QTimer timer;
    int messageNo = 1;
};

#endif

 main.cpp

#include <QApplication>

#include "sender.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Sender sender;
    sender.show();
    return app.exec();
}

 sender.cpp

#include <QtWidgets>
#include <QtNetwork>
#include <QtCore>

#include "sender.h"

Sender::Sender(QWidget *parent)
    : QWidget(parent)
{
    statusLabel = new QLabel(tr("Ready to broadcast datagrams on port 45454"));
    statusLabel->setWordWrap(true);

    startButton = new QPushButton(tr("&Start"));
    auto quitButton = new QPushButton(tr("&Quit"));

    auto buttonBox = new QDialogButtonBox;
    buttonBox->addButton(startButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);

//! [0]
    udpSocket = new QUdpSocket(this);
//! [0]

    connect(startButton, &QPushButton::clicked, this, &Sender::startBroadcasting);
    connect(quitButton, &QPushButton::clicked, this, &Sender::close);
    connect(&timer, &QTimer::timeout, this, &Sender::broadcastDatagram);

    auto mainLayout = new QVBoxLayout;
    mainLayout->addWidget(statusLabel);
    mainLayout->addWidget(buttonBox);
    setLayout(mainLayout);

    setWindowTitle(tr("Broadcast Sender"));
}

void Sender::startBroadcasting()
{
    startButton->setEnabled(false);
    timer.start(1000);
}

void Sender::broadcastDatagram()
{
    statusLabel->setText(tr("Now broadcasting datagram %1").arg(messageNo));
//! [1]
    QByteArray datagram = "Broadcast message " + QByteArray::number(messageNo);
    udpSocket->writeDatagram(datagram, QHostAddress::Broadcast, 45454);
//! [1]
    ++messageNo;
}

来分析下:

这里有个信号和槽,Qtimer关联了broadcastDatagram槽函数。发送广播包的就是这个槽函数。

来看下这个:

 这里就调用了udpSocket的writeDatagram,第二个参数就是广播报的,通过这种方式发送广播报。

 

以上是关于Qt文档阅读笔记-Broadcast Sender Example解析的主要内容,如果未能解决你的问题,请参考以下文章

Qt文档阅读笔记-Simple Chat Example解析

Qt文档阅读笔记-Qt5录音功能的实现

Qt文档阅读笔记-QScopedPointer解析及实例

Qt文档阅读笔记-QNetworkProxy::ProxyType解析(Qt设置Fiddler代理)

Qt文档阅读笔记-QNetworkProxy::ProxyType解析(Qt设置Fiddler代理)

Qt文档阅读笔记-QtConcurrent Progress Dialog Example解析