/
packetslices.go
106 lines (95 loc) · 2.76 KB
/
packetslices.go
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
103
104
105
106
package action
import (
"bytes"
"errors"
"strconv"
"github.com/breezedup/goserver/core/builtin/protocol"
"github.com/breezedup/goserver/core/netlib"
)
var (
SessionAttributeBigBuf = &PacketSlicesHandler{}
)
type PacketSlicesPacketFactory struct {
}
type PacketSlicesHandler struct {
}
func (this *PacketSlicesPacketFactory) CreatePacket() interface{} {
pack := &protocol.SSPacketSlices{}
return pack
}
func (this *PacketSlicesHandler) Process(s *netlib.Session, packetid int, data interface{}) error {
if packetslices, ok := data.(*protocol.SSPacketSlices); ok {
seqNo := int(packetslices.GetSeqNo())
if seqNo < 1 {
return errors.New("PacketSlicesHandler unexpect packet seq:" + strconv.Itoa(seqNo))
}
totalSize := int(packetslices.GetTotalSize())
if totalSize > s.GetSessionConfig().MaxPacket {
return errors.New("PacketSlicesHandler exceed MaxPacket size:" + strconv.Itoa(s.GetSessionConfig().MaxPacket) + " size=" + strconv.Itoa(totalSize))
}
attr := s.GetAttribute(SessionAttributeBigBuf)
if seqNo == 1 {
if attr == nil {
attr = bytes.NewBuffer(make([]byte, 0, packetslices.GetTotalSize()))
s.SetAttribute(SessionAttributeBigBuf, attr)
}
}
if seqNo > 1 {
if attr == nil {
return errors.New("PacketSlicesHandler Incorrect packet seq, expect seq=1")
}
} else if attr == nil {
return errors.New("PacketSlicesHandler get bytesbuf failed")
}
buf := attr.(*bytes.Buffer)
if seqNo == 1 {
buf.Reset()
}
if buf.Len() != int(packetslices.GetOffset()) {
return errors.New("PacketSlicesHandler get next packet offset error")
}
buf.Write(packetslices.GetPacketData())
if buf.Len() == totalSize {
packetid, pck, err := netlib.UnmarshalPacket(buf.Bytes())
if err != nil {
return err
}
h := netlib.GetHandler(packetid)
if h != nil {
h.Process(s, packetid, pck)
}
}
}
return nil
}
func init() {
netlib.RegisterHandler(int(protocol.CoreBuiltinPacketID_PACKET_SS_SLICES), &PacketSlicesHandler{})
netlib.RegisterFactory(int(protocol.CoreBuiltinPacketID_PACKET_SS_SLICES), &PacketSlicesPacketFactory{})
netlib.DefaultBuiltinProtocolEncoder.PacketCutor = func(data []byte) (packid int, packs []interface{}) {
var (
offset = 0
sendSize = 0
seqNo = 1
totalSize = len(data)
restSize = len(data)
)
packid = int(protocol.CoreBuiltinPacketID_PACKET_SS_SLICES)
for restSize > 0 {
sendSize = restSize
if sendSize > netlib.MaxPacketSize-128 {
sendSize = netlib.MaxPacketSize - 128
}
pack := &protocol.SSPacketSlices{
SeqNo: int32(seqNo),
TotalSize: int32(totalSize),
Offset: int32(offset),
PacketData: data[offset : offset+sendSize],
}
seqNo++
restSize -= sendSize
offset += sendSize
packs = append(packs, pack)
}
return
}
}