今天是除夕夜,祝大家除夕快乐
目录
效果图
QUdpSocket手册选读
关键词lightweight, unreliable, datagram-oriented, connectionless protocol,说明只能用在可靠性不高的场合,如果服务器未收到请求,客户端不会重发。
QQ微信就是UDP发送消息,所以有时候会出现收不到消息的情况。
UDP节选:
UDP 是User Datagram Protocol的简称, 中文名是用户数据报协议,是OSI(Open System Interconnection,开放式系统互联) 参考模型中一种无连接的传输层协议,提供面向事务的简单不可靠信息传送服务,IETF RFC 768 [1] 是UDP的正式规范。UDP在IP报文的协议号是17。
UDP协议与TCP协议一样用于处理数据包,在OSI模型中,两者都位于传输层,处于IP协议的上一层。UDP有不提供数据包分组、组装和不能对数据包进行排序的缺点,也就是说,当报文发送之后,是无法得知其是否安全完整到达的。UDP用来支持那些需要在计算机之间传输数据的网络应用。包括网络视频会议系统在内的众多的客户/服务器模式的网络应用都需要使用UDP协议。UDP协议从问世至今已经被使用了很多年,虽然其最初的光彩已经被一些类似协议所掩盖,但即使在今天UDP仍然不失为一项非常实用和可行的网络传输层协议。
许多应用只支持UDP,如:多媒体数据流,不产生任何额外的数据,即使知道有破坏的包也不进行重发。当强调传输性能而不是传输的完整性时,如:音频和多媒体应用,UDP是最好的选择。在数据传输时间很短,以至于此前的连接过程成为整个流量主体的情况下,UDP也是一个好的选择。
udpserver.h
#ifndef UDPSEVER_H
#define UDPSEVER_H
#include <QDialog>
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QTimer>
#include <QUdpSocket>
#include <QHostAddress>
class UDPSever : public QDialog
{
Q_OBJECT
public:
UDPSever(QWidget *parent = nullptr);
~UDPSever();
public slots:
void StartBtnClicked();
void timeout();
private:
QLabel *TimerLabel;
QLineEdit *TextLineEdit;
QPushButton *StartBtn;
QVBoxLayout *mainLayout;
int port;
bool isStarted;
QUdpSocket *udpSocket;
QTimer *timer;
};
#endif // UDPSEVER_H
udpserver.cpp.
#include "udpsever.h"
UDPSever::UDPSever(QWidget *parent)
: QDialog(parent)
{
setWindowIcon(QIcon("icon.png"));
setWindowTitle(QStringLiteral("UDP服务器"));
resize(300,150);
//布局设计
TimerLabel = new QLabel(QStringLiteral("计时器:"),this);
TextLineEdit = new QLineEdit(this);
StartBtn = new QPushButton(QStringLiteral("开始"),this);
mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(TimerLabel);
mainLayout->addWidget(TextLineEdit);
mainLayout->addWidget(StartBtn);
//点击开始键信号
connect(StartBtn,SIGNAL(clicked()),this,SLOT(StartBtnClicked()));
port = 5555;//设置UDP端口参数,服务器定时向此端口发送广播信息
isStarted = false;
udpSocket = new QUdpSocket(this);
timer = new QTimer(this);
//定时发送广播信息
connect(timer,SIGNAL(timerout),this,SLOT(timerout()));
}
UDPSever::~UDPSever()
{
}
void UDPSever::StartBtnClicked(){
if(!isStarted){
StartBtn->setText(QStringLiteral("停止"));
timer->start(1000);//1000ms为单位开始计时
isStarted = true;
}else{
StartBtn->setText(QStringLiteral("开始"));
isStarted = false;
timer->stop();
}
}
void UDPSever::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;
}
}