标签:
一 UDP介绍
UDP是一种简单轻量级的传输层协议,提供无连接的,不可靠的报文传输。适合下面4种情况:
网络数据大多为短消息。
拥有大量客户端。
对数据安全性无特殊要求
网络负担非常重,但对响应速度要求高。
二 基于udp协议的c/s编程模型(广播),组播的话,明天再看。
客户端:
class Sender : public QObject { Q_OBJECT //可以使用信号和槽 public: explicit Sender(QObject *parent = 0); ~Sender();//虚构函数无返回值 void start(); public slots: void broadcastDatagram(); private: QUdpSocket *udpSocket;//包含 <QtNetwork/qudpsocket.h> QTimer *timer; int messageNo; };
在使用udp tcp时,qt的.pro文件中要加上 QT +=network.
具体实现:
#include "sender.h" Sender::Sender(QObject *parent) : QObject(parent) { timer = new QTimer(this); udpSocket = new QUdpSocket(this); connect(timer,SIGNAL(timeout()),this,SLOT(broadcastDatagram())); messageNo = 1; } void Sender::start() { timer->start(1000); } void Sender::broadcastDatagram() { qDebug()<<(tr("Begin Broadcast: %1").arg(messageNo)); QByteArray datagram = "BroadCast Message:" + QByteArray::number(messageNo); udpSocket->writeDatagram(datagram.data(),datagram.size(),QHostAddress::Broadcast,44444); ++messageNo; } Sender::~Sender() { delete timer; delete udpSocket;//是否删除connect? }
udpSocket->writeDatagram(datagram.data(),datagram.size(),QHostAddress::Broadcast,44444);
函数原型:writeDatagram(const char* data,qint64 size,const QHostAddress &address,quint16 port)
函数功能:将数据包发出
函数参数:数据包自身,数据包大小,发送到的地址,端口。
接收端:
class Receiver : public QObject { Q_OBJECT public: explicit Receiver(QObject *parent = 0); ~Receiver(); signals: public slots: void processPendingDatagrams(); private: QUdpSocket *udpSocket; };
具体实现:
#include "receiver.h" Receiver::Receiver(QObject *parent) : QObject(parent) { udpSocket = new QUdpSocket(this); udpSocket->bind(44444); connect(udpSocket,SIGNAL(readyRead()),this,SLOT(processPendingDatagrams())); } void Receiver::processPendingDatagrams() { while(udpSocket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(udpSocket->pendingDatagramSize()); udpSocket->readDatagram(datagram.data(),datagram.size()); qDebug() << (tr("Receice Data: \"%1\"").arg(datagram.data())); } } Receiver::~Receiver() { delete udpSocket; }
当接受到数据包时,QUdpSocket会发出readyRead()信号。我关联了processPendingDatagrams()。
先用hasPendingDatagrams()判断是否有可供读取的数据。若有,则用pendingDatagramSize()开辟一个缓冲区。
最后,用readDatagram()将报文读取到缓冲区中。
标签:
原文地址:http://www.cnblogs.com/feng-qing-yang/p/5860220.html