udpserver.h
/**
* 书本:【Qt5开发及实例】
* 功能:实现服务器端的编程
* 文件:udpserver.h
* 时间:2015年2月5日21:05:21
* 作者:cutter_point
*/
#ifndef UDPSERVER_H
#define UDPSERVER_H
#include <QDialog>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QTimer>
#include <QUdpSocket>
class UdpServer : public QDialog
{
Q_OBJECT
public:
UdpServer(QWidget *parent = 0, Qt::WindowFlags f = 0);
~UdpServer();
public slots:
void StartBtnClicked();
void timeout();
private:
QLabel *TimerLabel; //计时器标签
QLineEdit *TextLineEdit; //显示
QPushButton *StartBtn; //开始按钮
QVBoxLayout *mainLayout; //布局
int port; //UDP端口号
bool isStarted; //判断是否开始计算
QUdpSocket *udpSocket;
QTimer *timer; //每隔一段时间就发送广播
};
#endif // UDPSERVER_H
udpserver.cpp
/**
* 书本:【Qt5开发及实例】
* 功能:实现服务器端的编程
* 文件:udpserver.cpp
* 时间:2015年2月5日21:05:21
* 作者:cutter_point
*/
#include "udpserver.h"
#include <QHostAddress>
UdpServer::UdpServer(QWidget *parent,Qt::WindowFlags f)
: QDialog(parent, f)
{
setWindowTitle(tr("UDP Server"));
TimerLabel = new QLabel(tr("计时器:"),this);
TextLineEdit = new QLineEdit(this);
StartBtn = new QPushButton(tr("开始:"),this);
mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(TimerLabel);
mainLayout->addWidget(TextLineEdit);
mainLayout->addWidget(StartBtn); //布置好界面显示
connect(StartBtn, SIGNAL(clicked()), this, SLOT(StartBtnClicked())); //点击按钮触发事件
//设定UDP端口
port = 5555;
isStarted = false; //开始是没有启动
udpSocket = new QUdpSocket(this); //一个套接字
timer = new QTimer(this); //计时器
connect(timer, SIGNAL(timeout()), this, SLOT(timeout()));
}
// void StartBtnClicked();
void UdpServer::StartBtnClicked()
{
if(!isStarted) //如果计时还没有启动
{
StartBtn->setText(tr("停止"));
timer->start(1000); //开始启动计时器并执行1000毫秒,也就是1秒
isStarted = true; //表示启动
}
else
{
StartBtn->setText(tr("开始:"));
isStarted = false;
timer->stop(); //停止计时
}
}
//void timeout();
void UdpServer::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;
}
}
UdpServer::~UdpServer()
{
}
结果