Qt packet abstraction based on TCP network program
I have no experience before. When sending data packets, the packet header and other information are all implemented by redefining a struct. Different protocol packages have different structs. The result is as follows: how many upper-layer business protocol packages are there? I will re-define a new structure corresponding to the ending of the packet header, which is very difficult ....... amount ....
Now, I have thought about a new way to abstract the "packet" process and use Qt's QByteArray to operate streaming data (which is quite convenient)
. H
# Ifndef PACKET_H # define PACKET_H # include <QObject> # include <QByteArray> # define FrontPacket "KT" # define EndPacket "END" // package data, add the header package length flag to verify class Packet: public QObject {Q_OBJECTpublic: explicit Packet (QObject * parent = 0); static QByteArray Pack (QByteArray data); // Packet }; # endif // PACKET_H
. Cpp
#include "packet.h"Packet::Packet(QObject *parent) : QObject(parent){}QByteArray Packet::Pack(QByteArray data){ QByteArray pack; pack.append(FrontPacket); quint32 len = 4 + data.size() + 4 + 3; pack.append(reinterpret_cast<const char*>(&len), 4); quint32 flag = 0; pack.append(reinterpret_cast<const char*>(&flag), 4); pack.append(data); quint32 crc = 0; pack.append(reinterpret_cast<const char*>(&crc), 4); pack.append(EndPacket); return pack;}
Then, when operating on the upper-layer interface, you can use the defined upper-layer protocol struct object to directly convert it to the byte stream QByteArray type and then send the data sending interface to the underlying network. In the underlying data sending interface, before sending data, pass the transmitted protocol data packet to the encapsulated static class member Pack () for processing. Then, you can directly send the returned value.
Advantage: for upper-layer businesses, as long as the upper-layer protocol data is encapsulated, a unified data sending interface at the bottom of the network can be called to send packets (this was done before this setback: the underlying network provides different interface methods for different protocol packages. Then, each time a new protocol is added, a member function is added. Every time a protocol is deleted, it is necessary ..... 111111111111111111)
Complete ....................................... ..............
From: http://www.cnblogs.com/jianc/archive/2013/01/29/2881651.html