【Qt點滴】UDP協議實例:簡易廣播實現

Qt5實現的簡易UDP廣播程序,學習Qt 下UDP協議的基本使用。函數

建立兩個工程,命名UDPclient和UDPserver.學習

又server發送廣播,client負責接收。測試

 

------------ui

建立UDPserver時,選擇dialog窗口類。this

並用Qt設計器建立界面。spa

 

textedit用來輸入廣播的消息。設計

start按鈕開始廣播。3d

 

在.pro工程文檔加入:code

QT       += network

 

dialog.h中,包含頭文件:server

#include <QUdpSocket>
#include <QTimer>

及槽函數:

public slots:
    void StartBtnClicked();
    void TimeOut();

 

 

聲明變量:

private:
    int port ;
    bool isStarted;
    QUdpSocket *udpSocket;
    QTimer *timer;

 

dialog.cpp中:

包含頭文件:

#include <QHostAddress>

 

在構造函數中添加:

    this->setWindowTitle("UDP Server");

    this->timer = new QTimer();
    this->udpSocket = new QUdpSocket;
    this->isStarted = false;
    this->port = 45454;

    connect(this->timer,SIGNAL(timeout()),this,SLOT(TimeOut()));
    connect(this->ui->StartBtn,SIGNAL(clicked()),this,SLOT(StartBtnClicked()));

鏈接信號槽;

 

實現槽函數:

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

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

這樣,點擊發送按鈕後觸發StartBtnDClicked()函數,並初始化定時器爲1000ms,即每隔一秒觸發TimeOut()函數發送廣播;

發送過程當中再次點擊按鈕,發送中止;

 

其中,發送廣播:writeDatagram(msg.toLatin1(),msg.length(),QHostAddress::Broadcast,port),QHostAddress::Broadcast獲取地址,port定義1024至65536之間任意值便可;

 

 

-----------

而後是client,接收端;

在.pro工程文檔加入:

QT       += network

 

 建立界面:

textEdit用來顯示接收到的廣播;

 

dialog.h中,包含頭文件:

#include <QUdpSocket>

槽函數:

public slots:
    void CloseBtnClicked();
    void processPendingDatagram();

聲明:

private:
    int port;
    QUdpSocket *UdpSocket;

 

dialg.cpp中:

 

包含

#include <QHostAddress>

構造函數中添加:

    this->setWindowTitle("UDP client");

    this->UdpSocket = new QUdpSocket;
    this->port = 45454;

    this->UdpSocket->bind(port,QUdpSocket::ShareAddress);

    connect(this->ui->CloseBtn,SIGNAL(clicked()),this,SLOT(CloseBtnClicked()));
    connect(this->UdpSocket,SIGNAL(readyRead()),this,SLOT(processPendingDatagram()));

 

實現槽函數:

void Dialog::CloseBtnClicked()
{
    this->close();
}

void Dialog::processPendingDatagram()
{
    while(this->UdpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(this->UdpSocket->pendingDatagramSize());
        this->UdpSocket->readDatagram(datagram.data(),datagram.size());
        this->ui->ReceiveTextEdit->insertPlainText(datagram);
    }
}

當有廣播時,將收到的消息顯示在文本編輯框中;

 

---------

 

運行效果:

 

打開一個client和一個server:

 

輸入 「 Hello world!  " 測試;

 

 

Moran @ 2014.6.2

相關文章
相關標籤/搜索