此例子展示了使用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,第二个参数就是广播报的,通过这种方式发送广播报。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/qq78442761/article/details/121231426
内容来源于网络,如有侵权,请联系作者删除!