Qt5实现的简易UDP广播程序,学习Qt 下UDP协议的基本使用。
创建两个工程,命名UDPclient和UDPserver.
又server发送广播,client负责接收。
------------
创建UDPserver时,选择dialog窗口类。
并用Qt设计器创建界面。
textedit用来输入广播的消息。
start按钮开始广播。
在.pro工程文档加入:
QT += network
dialog.h中,包含头文件:
#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
Qt点滴:UDP协议的简易广播实例,布布扣,bubuko.com
原文:http://www.cnblogs.com/moranBlogs/p/3764562.html