1、功能描述
功能类似于电台发报机或收音机一样,服务端会定时的向某个客户端(广播地址:端口)发出一段字符串文字,客户端在网络畅通情况下能够正确接收到信息,但不进行反馈。
创建两个Qt对话框项目,一个作为服务端,一个作为客户端。
2、服务端主要代码
udpserver.h
#ifndef UDPSERVER_H
#define UDPSERVER_H
#include <QDialog>
#include <QUdpSocket>
#include <QTimer>
QT_BEGIN_NAMESPACE
namespace Ui { class Udpserver; }
QT_END_NAMESPACE
class Udpserver : public QDialog
{
Q_OBJECT
public:
Udpserver(QWidget *parent = nullptr);
~Udpserver();
private slots:
void on_SEpushButton_clicked();
void timeout();
private:
Ui::Udpserver *ui;
quint16 m_nPort;
bool m_bStarted;
QUdpSocket *m_udpSocket;
QTimer *m_timer;
};
#endif
udpserver.cpp
#include "udpserver.h"
#include "ui_udpserver.h"
#pragma execution_character_set("utf-8")
Udpserver::Udpserver(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Udpserver)
{
ui->setupUi(this);
m_nPort = 5555;
m_bStarted=false;
m_udpSocket = new QUdpSocket(this);
m_timer = new QTimer(this);
connect(m_timer,SIGNAL(timeout()),this,SLOT(timeout()));
}
Udpserver::~Udpserver()
{
delete ui;
}
void Udpserver::on_SEpushButton_clicked()
{
if(m_bStarted)
{
ui->SEpushButton->setText(tr("开始"));
m_timer->stop();
m_bStarted =false;
}
else
{
ui->SEpushButton->setText(tr("停止"));
m_timer->start(1000);
m_bStarted =true;
}
}
void Udpserver::timeout()
{
QString msg = ui->ContentLineEdit->text();
if(msg=="")
{
return;
}
qint64 qLength = m_udpSocket->writeDatagram(msg.toLatin1(),msg.length(),QHostAddress::Broadcast,m_nPort);
int length = static_cast<int>(qLength);
if(length != msg.length())
{
return;
}
}
3、客户端主要代码 udpclient.h
#ifndef UDPCLIENT_H
#define UDPCLIENT_H
#include <QDialog>
#include <QMessageBox>
#include <QUdpSocket>
#include <QHostAddress>
QT_BEGIN_NAMESPACE
namespace Ui { class udpclient; }
QT_END_NAMESPACE
class udpclient : public QDialog
{
Q_OBJECT
public:
udpclient(QWidget *parent = nullptr);
~udpclient();
private slots:
void on_pushButton_clicked();
void dataReceived();
private:
Ui::udpclient *ui;
quint16 m_nPort;
QUdpSocket *m_udpSocket;
};
#endif
udpclient.cpp
#include "udpclient.h"
#include "ui_udpclient.h"
#pragma execution_character_set("utf-8")
udpclient::udpclient(QWidget *parent)
: QDialog(parent)
, ui(new Ui::udpclient)
{
ui->setupUi(this);
m_nPort = 5555;
m_udpSocket = new QUdpSocket(this);
connect(m_udpSocket,SIGNAL(readyRead()),this,SLOT(dataReceived()));
bool bResult = m_udpSocket->bind(m_nPort);
if(!bResult)
{
QMessageBox::information(this,tr("error:"),tr("UDP Socket create error!"));
return;
}
}
udpclient::~udpclient()
{
delete ui;
}
void udpclient::on_pushButton_clicked()
{
close();
}
void udpclient::dataReceived()
{
while (m_udpSocket->hasPendingDatagrams())
{
QByteArray datagram;
qint64 qLength = m_udpSocket->pendingDatagramSize();
int length = static_cast<int>(qLength);
datagram.resize(length);
m_udpSocket->readDatagram(datagram.data(),datagram.size());
QString msg = datagram.data() + tr("\n");
ui->textEdit->insertPlainText(msg);
}
}
|