This repository was archived by the owner on Mar 19, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOuterMsg.go
More file actions
104 lines (89 loc) · 2.16 KB
/
OuterMsg.go
File metadata and controls
104 lines (89 loc) · 2.16 KB
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
package core
import (
"encoding/binary"
"io"
)
const (
IdLen = OuteridLen
BodyLenLen = 8
)
/*
OuterMsg 报文格式
(2016/9/1 9:21:20,192.127.21.12:23423)
bodylen:
body...
*/
type OuterMsg struct {
Id Outerid
GoId Outerid
BodyLen uint64
Body []byte
}
func (this *OuterMsg) WriteString(s string) *OuterMsg {
this.Body = []byte(s)
this.BodyLen = uint64(len([]byte(s)))
return this
}
func (this *OuterMsg) Write(bs []byte) *OuterMsg {
this.Body = bs
this.BodyLen = uint64(len(bs))
return this
}
// region 序列化
func (this *OuterMsg) Marshal() (bs []byte) {
bs = make([]byte, OuteridLen*2+8+int(this.BodyLen))
copy(bs[:OuteridLen], this.Id.Marshal())
copy(bs[OuteridLen:OuteridLen*2], this.GoId.Marshal())
binary.BigEndian.PutUint64(bs[OuteridLen*2:OuteridLen*2+8], this.BodyLen)
copy(bs[OuteridLen*2+8:], this.Body)
return
}
func (this OuterMsg) Read(reader io.Reader) (msg OuterMsg, err error) {
idbs := make([]byte, IdLen)
idlen, err := reader.Read(idbs)
if idlen != IdLen || !checkError(err, "Outerid error") {
return
}
Id, err := (Outerid{}).Unmarshal(idbs)
if !checkError(err, "Outerid error") {
return
}
msg.Id = *Id
goidbs := make([]byte, IdLen)
goidlen, err := reader.Read(goidbs)
if goidlen != IdLen || !checkError(err, "Outerid error") {
return
}
GoId, err := (Outerid{}).Unmarshal(goidbs)
if !checkError(err, "Outerid error") {
return
}
msg.GoId = *GoId
bodylenbs := make([]byte, BodyLenLen)
bodylenlen, err := reader.Read(bodylenbs)
if bodylenlen != BodyLenLen || !checkError(err, "bodylen error") {
return
}
bodylen := binary.BigEndian.Uint64(bodylenbs)
body := make([]byte, bodylen)
Blen, err := reader.Read(body)
if Blen != int(bodylen) || !checkError(err, "body error") {
return
}
msg.BodyLen = bodylen
msg.Body = body
return
}
func (this OuterMsg) Unmarshal(bs []byte) (msg OuterMsg, err error) {
id := &Outerid{}
goid := &Outerid{}
id, err = (Outerid{}).Unmarshal(bs[:IdLen])
goid, err = (Outerid{}).Unmarshal(bs[IdLen : IdLen*2])
msg.Id = *id
msg.GoId = *goid
msg.BodyLen = binary.BigEndian.Uint64(bs[IdLen*2 : IdLen*2+BodyLenLen])
msg.Body = bs[IdLen*2+BodyLenLen:]
//
return
}
// endregion