QT开发之UDP协议

众所周知,UDP协议是轻量级,不可靠,面向数据包,无连接的协议.通过两个应用程序,一个实现发送数据,一个接受数据.


新建Qt Gui应用项目,工程文件后面添加   QT  +=network.  以后就不讲怎么创建工程了,直接贴核心代码就行.


sender.h

#ifndef SENDER_H
#define SENDER_H

#include <QDialog>
class QUdpSocket;

namespace Ui {
    class Sender;
}

class Sender : public QDialog
{
    Q_OBJECT

public:
    explicit Sender(QWidget *parent = 0);
    ~Sender();

private slots:
    void on_pushButton_clicked();

private:
    Ui::Sender *ui;
    QUdpSocket *sender;
};

#endif // SENDER_H

注意定义了一个按键信号槽.需要在ui设计界面添加一个按钮.


sender.cpp

#include "sender.h"
#include "ui_sender.h"
#include <QtNetwork>

Sender::Sender(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Sender)
{
    ui->setupUi(this);
    sender = new QUdpSocket(this);
}

Sender::~Sender()
{
    delete ui;
}

void Sender::on_pushButton_clicked()
{
    QByteArray data = "hello world!";
    sender->writeDatagram(data.data(), data.size(),
                          QHostAddress::Broadcast, 8080);
}

receiver.h

#ifndef RECEIVER_H
#define RECEIVER_H

#include <QDialog>
class QUdpSocket;

namespace Ui {
    class Receiver;
}

class Receiver : public QDialog
{
    Q_OBJECT

public:
    explicit Receiver(QWidget *parent = 0);
    ~Receiver();

private:
    Ui::Receiver *ui;
    QUdpSocket *receiver;

private slots:
    void processPendingDatagram();
};

#endif // RECEIVER_H

receiver.cpp

#include "receiver.h"
#include "ui_receiver.h"
#include <QtNetwork>

Receiver::Receiver(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Receiver)
{
    ui->setupUi(this);
    receiver = new QUdpSocket(this);
    receiver->bind(8080, QUdpSocket::ShareAddress);
    connect(receiver, SIGNAL(readyRead()), this, SLOT(processPendingDatagram()));
}

Receiver::~Receiver()
{
    delete ui;
}


void Receiver::processPendingDatagram()
{

    while(receiver->hasPendingDatagrams())
    {
        QByteArray data;

        data.resize(receiver->pendingDatagramSize());

        receiver->readDatagram(data.data(), data.size());
        ui->label->setText(data);
    }
}

需要在ui上添加一个label的标签,用于显示接收到的数据.


上面程序中使用bing()函数来绑定IP地址和端口号.每当有数据到来时候,QUdpSocket都会发射一个readyRead()信号,这样就可以在自定义槽中读取数据,我们定义的信号槽函数是processPendingDatagram()



 

                                                                                                                   文章出自:Linux_Google       

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页