简单协议可以使用:json + base64(有需要)
#ifndef UDPSOCKET_H
#define UDPSOCKET_H
#include <QObject>
#include <QMap>
#include <QHostAddress>
#include <functional>
class QUdpSocket;
class UdpSocket : public QObject
{
Q_OBJECT
public:
struct Address {
Address() : port(0) { }
Address(const QHostAddress &_host, int _port) : host(_host), port(_port) { }
QHostAddress host;
int port;
};
typedef std::function<void(quint64 number, const QByteArray &data)> ReveivedHandleFunc;
explicit UdpSocket(QObject *parent = 0);
void init(int port, int isServer, const ReveivedHandleFunc &func);
void send(quint64 number, const QByteArray &data);
private slots:
void slotReadPendingData();
private:
void processTheDatagram(const QByteArray &data);
private:
QUdpSocket *m_udp;
int m_port;
bool m_isServer;
ReveivedHandleFunc m_receivedHandleFunc;
quint64 m_number;
QMap<quint64, Address> m_msg;
};
#endif // UDPSOCKET_H
#include "udpsocket.h"
#include <QHostAddress>
#include <QUdpSocket>
UdpSocket::UdpSocket(QObject *parent)
: QObject(parent), m_udp(NULL), m_port(0), m_isServer(false), m_number(0)
{
}
void UdpSocket::init(int port, int isServer, const ReveivedHandleFunc &func)
{
if (NULL == m_udp) {
m_udp = new QUdpSocket(this);
connect(m_udp, SIGNAL(readyRead()), this, SLOT(slotReadPendingData()));
if (isServer) {
m_udp->bind(QHostAddress::LocalHost, port);
}
}
m_port = port;
m_isServer = isServer;
m_receivedHandleFunc = func;
}
void UdpSocket::send(quint64 number, const QByteArray &data)
{
if (!m_udp) {
return;
}
if (m_isServer) {
if (m_msg.contains(number)) {
Address address = m_msg[number];
m_msg.remove(number);
m_udp->writeDatagram(data, address.host, address.port);
}
} else {
m_udp->writeDatagram(data, QHostAddress::LocalHost, m_port);
}
}
void UdpSocket::slotReadPendingData()
{
if (NULL == m_udp) {
return;
}
while (m_udp->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(m_udp->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
if (m_udp->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort) >= 0) {
++m_number;
if (m_msg.size() > 3000) {
m_msg.clear();
}
m_msg[m_number] = Address(sender, senderPort);
if (m_receivedHandleFunc) {
m_receivedHandleFunc(m_number, datagram);
}
}
}
}