Qt--基于UDP的网络广播

 用户数据报协议(User Data Protocol,UDP)是一种简单轻量级、不可靠、面向数据报、无连接的传输协议,可以应用在可靠性不是十分重要的场合,如短消息、广播信息等。
 UDP客户端向UDP服务器发送一定长度的请求报文,报文大小的限制于各系统的协议实现有关,但不得超过其下层IP协议规定的64KB;UDP服务器同样以报文形式作出响应。如果服务器未收到此请求,客户端进行重发,因此报文的传输是不可靠的。
Qt中通过QUdpSocket类实现UDP协议的编程。
UDP适用于以下几种情况:

  • 网络数据大多是短消息
  • 拥有大量的 客户端
  • 对数据安全性无特殊要求
  • 网络负担非常重,但对响应速度要求高

服务器端编程

MainWindow.h 头文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QDialog>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QUdpSocket>
#include <QTimer>


class UDP_Server : public QDialog
{
    Q_OBJECT

public:
    UDP_Server(QWidget *parent = 0,Qt::WindowFlags f=0);
    ~UDP_Server();

public slots:
    void StartBtnClicked();//按键点击槽函数声明
    void timeout();


private:
    int port;//端口声明
    bool isStarted;
    QUdpSocket *udpSocket;//网络Socket声明
    QTimer *timer;

    QLabel *TimerLabel;
    QLineEdit *TextLineEdit;
    QPushButton *StartBtn;
    QVBoxLayout *mainLayout;

};

#endif // MAINWINDOW_H

main.cpp 的内容

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    UDP_Server w;
    w.show();

    return a.exec();
}

Mainwindow.cpp 内容

#include "mainwindow.h"
#include <QHostAddress>

UDP_Server::UDP_Server(QWidget *parent,Qt::WindowFlags f)
    : QDialog(parent,f)
{
    setWindowTitle("UDP Server");//设置窗体的标题
    /*初始化各个控件*/
    TimerLabel = new QLabel(tr("Timer:"),this);
    TextLineEdit = new QLineEdit(this);
    StartBtn = new QPushButton(tr("Start"),this);
    /*设置布局*/
    mainLayout = new QVBoxLayout(this);
    mainLayout ->addWidget(TimerLabel);
    mainLayout ->addWidget(TextLineEdit);
    mainLayout ->addWidget(StartBtn);
    connect(StartBtn,SIGNAL(clicked()),this,SLOT(StartBtnClicked()));

    port =5555;
    isStarted=false;
    udpSocket = new QUdpSocket(this);
    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(timeout()));
}

UDP_Server::~UDP_Server()
{

}

void UDP_Server::StartBtnClicked()
{
    if(!isStarted)
    {
        StartBtn->setText(tr("Stop"));
        timer->start(1000);
        isStarted =true;
    }
    else
    {
        StartBtn->setText(tr("Start"));
        isStarted = false;
        timer->stop();
    }
}

void UDP_Server::timeout()
{
    QString msg = TextLineEdit->text();
    int length=0;
    if(msg=="")
    {
       return;
    }
    if((length=udpSocket->writeDatagram(msg.toLatin1(),msg.length(),QHostAddress::Broadcast,port))!=msg.length())
    {
        return;
    }
}

客户端编程

MainWindow.h的程序:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QDialog>
#include <QVBoxLayout>
#include <QTextEdit>
#include <QPushButton>
#include <QUdpSocket>



class UDP_Client : public QDialog
{
    Q_OBJECT

public:
    UDP_Client(QWidget *parent = 0);
    ~UDP_Client();
public slots:
    void CloseBtnClicked();
    void dataReceived();
    void CleanBtnClicked();
private:
    int port;
    QUdpSocket *udpSocket;
    QTextEdit *ReceiveTextEdit;
    QPushButton *CloseBtn;
    QPushButton *CleanBtn;
    QVBoxLayout *mainLayout;

};

#endif // MAINWINDOW_H

main.cpp的程序:

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    UDP_Client w;
    w.show();

    return a.exec();
}

MainWindow.cpp程序:

#include "mainwindow.h"
#include <QMessageBox>
#include <QHostAddress>


UDP_Client::UDP_Client(QWidget *parent)
    : QDialog(parent)
{
    setWindowTitle(tr("UDP Client"));
    /*初始化各个控件*/
    ReceiveTextEdit = new QTextEdit(this);
    CloseBtn = new QPushButton(tr("Close"),this);
    CleanBtn = new QPushButton(tr("Clean"),this);
    /*设置布局*/
    mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(ReceiveTextEdit);
    mainLayout->addWidget(CloseBtn);
    mainLayout->addWidget(CleanBtn);

    connect(CloseBtn,SIGNAL(clicked()),this,SLOT(CloseBtnClicked()));
    connect(CleanBtn,SIGNAL(clicked()),this,SLOT(CleanBtnClicked()));

    port =5555;

    udpSocket = new QUdpSocket(this);
    connect(udpSocket,SIGNAL(readyRead()),this,SLOT(dataReceived()));

    bool result=udpSocket->bind(port);
    if(!result)
    {
        QMessageBox::information(this,tr("error"),tr("udp socket create error!"));
        return;
    }
}

UDP_Client::~UDP_Client()
{

}

void UDP_Client::CloseBtnClicked()
{
    close();
}
void UDP_Client::CleanBtnClicked()//清空数据显示
{
    ReceiveTextEdit->clear();
}

void UDP_Client::dataReceived()
{
    while(udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());

        udpSocket->readDatagram(datagram.data(),datagram.size());
        QString msg=datagram.data();
        ReceiveTextEdit->insertPlainText(msg);
    }
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页