Qt程序分析_broadcastUDP

来源:互联网 发布:三维软件开发平台 编辑:程序博客网 时间:2024/05/21 15:00
E:\Qt\Qt5.5.0\Examples\Qt-5.5\network\broadcastsender
E:\Qt\Qt5.5.0\Examples\Qt-5.5\network\broadcastreceiver
#include <QtWidgets>#include <QtNetwork>#include "sender.h"Sender::Sender(QWidget *parent)    : QWidget(parent){    //UI布局    statusLabel = new QLabel(tr("Ready to broadcast datagrams on port 45454"));    //设置其文本显示自动换行,变化时自动调整每行的显示效果    statusLabel->setWordWrap(true);        startButton = new QPushButton(tr("&Start"));    quitButton = new QPushButton(tr("&Quit"));    buttonBox = new QDialogButtonBox;    buttonBox->addButton(startButton, QDialogButtonBox::ActionRole);    buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);    timer = new QTimer(this);//! [0]//! 初始化    udpSocket = new QUdpSocket(this);//! [0]    messageNo = 1;    connect(startButton, SIGNAL(clicked()), this, SLOT(startBroadcasting()));    connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));    connect(timer, SIGNAL(timeout()), this, SLOT(broadcastDatagram()));    QVBoxLayout *mainLayout = new QVBoxLayout;    mainLayout->addWidget(statusLabel);    mainLayout->addWidget(buttonBox);    setLayout(mainLayout);    setWindowTitle(tr("Broadcast Sender"));}

发报文函数:

void Sender::startBroadcasting(){    //点击一次strat后,变灰。禁止使用    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);    //通过writeDatagram发送报文    udpSocket->writeDatagram(datagram.data(), datagram.size(),                             QHostAddress::Broadcast, 45454);//! [1]    ++messageNo;}

函数原型:

    bool hasPendingDatagrams() const;    qint64 pendingDatagramSize() const;    qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *host = 0, quint16 *port = 0);    qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &host, quint16 port);//原始    inline qint64 writeDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)//重新的,不用写大小        { return writeDatagram(datagram.constData(), datagram.size(), host, port); }


接收数据程序:

#include <QtWidgets>#include <QtNetwork>#include "receiver.h"Receiver::Receiver(QWidget *parent)    : QWidget(parent){    //UI界面    statusLabel = new QLabel(tr("Listening for broadcasted messages"));    statusLabel->setWordWrap(true);    quitButton = new QPushButton(tr("&Quit"));//初始化,bind绑定端口号,选择绑定模式,这里是允许其他服务器绑定到相同地址和端口上    udpSocket = new QUdpSocket(this);    udpSocket->bind(45454, QUdpSocket::ShareAddress);//! [0]//一旦有数据可读,即收到数据。就发送readyRead()信号    connect(udpSocket, SIGNAL(readyRead()),            this, SLOT(processPendingDatagrams()));//! [1]    connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));    QHBoxLayout *buttonLayout = new QHBoxLayout;    buttonLayout->addStretch(1);    buttonLayout->addWidget(quitButton);    buttonLayout->addStretch(1);    QVBoxLayout *mainLayout = new QVBoxLayout;    mainLayout->addWidget(statusLabel);    mainLayout->addLayout(buttonLayout);    setLayout(mainLayout);    setWindowTitle(tr("Broadcast Receiver"));}


读取数据程序:

//读取收到的数据void Receiver::processPendingDatagrams(){//! [2]//! 是否有未读出的数据等待    while (udpSocket->hasPendingDatagrams()) {        QByteArray datagram;        //限定容器的大小为等待处理的数据包的大小,这样才能收到完整的数据(个人感觉可以限定UDP读取的大小就好)        datagram.resize(udpSocket->pendingDatagramSize());        udpSocket->readDatagram(datagram.data(), datagram.size());        statusLabel->setText(tr("Received datagram: \"%1\"")                             .arg(datagram.data()));    }//! [2]}
最终效果:



组播程序分析:

UI编写

#include <QtWidgets>#include <QtNetwork>#include "sender.h"Sender::Sender(QWidget *parent)    : QDialog(parent){    //设置组播地址    groupAddress = QHostAddress("239.255.43.21");    statusLabel = new QLabel(tr("Ready to multicast datagrams to group %1 on port 45454").arg(groupAddress.toString()));    ttlLabel = new QLabel(tr("TTL for multicast datagrams:"));    ttlSpinBox = new QSpinBox;    ttlSpinBox->setRange(0, 255);    QHBoxLayout *ttlLayout = new QHBoxLayout;    ttlLayout->addWidget(ttlLabel);    ttlLayout->addWidget(ttlSpinBox);    startButton = new QPushButton(tr("&Start"));    quitButton = new QPushButton(tr("&Quit"));    buttonBox = new QDialogButtonBox;    buttonBox->addButton(startButton, QDialogButtonBox::ActionRole);    buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);    timer = new QTimer(this);    udpSocket = new QUdpSocket(this);    messageNo = 1;    //TTL下拉框改变了的时候    connect(ttlSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ttlChanged(int)));    connect(startButton, SIGNAL(clicked()), this, SLOT(startSending()));    connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));    connect(timer, SIGNAL(timeout()), this, SLOT(sendDatagram()));    QVBoxLayout *mainLayout = new QVBoxLayout;    mainLayout->addWidget(statusLabel);    mainLayout->addLayout(ttlLayout);    mainLayout->addWidget(buttonBox);    setLayout(mainLayout);    setWindowTitle(tr("Multicast Sender"));    ttlSpinBox->setValue(1);}

发送数据程序:

//设置UDP的TTL时间void Sender::ttlChanged(int newTtl){    udpSocket->setSocketOption(QAbstractSocket::MulticastTtlOption, newTtl);}//每1秒发送一次数据void Sender::startSending(){    startButton->setEnabled(false);    timer->start(1000);}//发送报文void Sender::sendDatagram(){    statusLabel->setText(tr("Now sending datagram %1").arg(messageNo));    QByteArray datagram = "Multicast message " + QByteArray::number(messageNo);    udpSocket->writeDatagram(datagram.data(), datagram.size(),                             groupAddress, 45454);    ++messageNo;}


接收组播数据程序:

几乎同上

#include <QtWidgets>#include <QtNetwork>#include "receiver.h"Receiver::Receiver(QWidget *parent)    : QDialog(parent){    //初始化组播地址    //组播地址:224.0.0.0到239.255.255.255    //类似IP中的私网地址:239.0.0.0~239.255.255.255    groupAddress = QHostAddress("239.255.43.21");    statusLabel = new QLabel(tr("Listening for multicasted messages"));    quitButton = new QPushButton(tr("&Quit"));    //初始化,绑定IP,端口号    udpSocket = new QUdpSocket(this);    udpSocket->bind(QHostAddress::AnyIPv4, 45454, QUdpSocket::ShareAddress);    //建立组播    udpSocket->joinMulticastGroup(groupAddress);    //有数据等待时,发信号,等待数据接收    connect(udpSocket, SIGNAL(readyRead()),            this, SLOT(processPendingDatagrams()));    connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));    QHBoxLayout *buttonLayout = new QHBoxLayout;    buttonLayout->addStretch(1);    buttonLayout->addWidget(quitButton);    buttonLayout->addStretch(1);    QVBoxLayout *mainLayout = new QVBoxLayout;    mainLayout->addWidget(statusLabel);    mainLayout->addLayout(buttonLayout);    setLayout(mainLayout);    setWindowTitle(tr("Multicast Receiver"));}//数据接收void Receiver::processPendingDatagrams(){    //有等待数据时    while (udpSocket->hasPendingDatagrams()) {        QByteArray datagram;        //限制大小为等待处理的数据大小,这样才能接收到完整的数据        datagram.resize(udpSocket->pendingDatagramSize());        //读取数据        udpSocket->readDatagram(datagram.data(), datagram.size());        statusLabel->setText(tr("Received datagram: \"%1\"")                             .arg(datagram.data()));    }}
结果图:






0 0
原创粉丝点击