【Qt5开发及实例】29、实现服务器端的编程,UDP协议

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()
{

}

结果




  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值