-
Notifications
You must be signed in to change notification settings - Fork 0
/
packet.cpp
102 lines (87 loc) · 2.04 KB
/
packet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "packet.h"
Packet::Packet(PacketType_t type)
{
header_.length = 0;
header_.type = type;
header_.body_checksum = 0;
header_.head_checksum = 0;
}
Packet::~Packet()
{
}
quint32 Packet::getLength()
{
return header_.length;
}
quint32 Packet::getType()
{
return header_.type;
}
const char* Packet::getPayload()
{
return payload_;
}
void Packet::getHeader(QDataStream& stream)
{
stream<<header_.length;
stream<<header_.type;
stream<<header_.body_checksum;
stream<<header_.head_checksum;
}
void Packet::setHeader(QDataStream& stream)
{
quint32 length;
stream>>length;
quint32 type;
stream>>type;
quint16 bd_chk;
stream>>bd_chk;
quint16 hd_chk;
stream>>hd_chk;
header_.length = length;
header_.type = type;
header_.body_checksum = bd_chk;
header_.head_checksum = hd_chk;
}
void Packet::setHeader(message_header_t h)
{
header_ = h;
}
bool Packet::checkHeader()
{
bool ok = false;
quint16 headerChecksum = header_.head_checksum;
header_.head_checksum = 0;
quint16 hchk = fletcher16((quint8*)&header_,HEADER_LENGTH);
ok = hchk == headerChecksum;
header_.head_checksum = headerChecksum;
return ok;
}
QDataStream& operator<<(QDataStream& stream, Packet& pack)
{
pack.build();
pack.getHeader(stream);
stream<<pack.getPayload();
return stream;
}
QTcpSocket& operator<<(QTcpSocket& sock, Packet& pack)
{
pack.build();
sock.write((char*)&pack.header_, Packet::HEADER_LENGTH);
sock.write(pack.getPayload(),pack.header_.length - Packet::HEADER_LENGTH);
return sock;
}
QDataStream& operator>>(QDataStream& stream, Packet& pack)
{
pack.getHeader(stream);
return stream;
}
void Packet::build()
{
header_.body_checksum = 0;
header_.head_checksum = 0;
//+1 for null char not counted in QString.Size()
header_.length = Packet::HEADER_LENGTH + payloadSize();
header_.body_checksum = fletcher16((quint8*)getPayload(),payloadSize());
header_.head_checksum = fletcher16((quint8*)&header_,12);
}