-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
113 lines (94 loc) · 2.48 KB
/
message.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
107
108
109
110
111
112
113
package fnet
import (
"bytes"
"encoding/binary"
"github.com/fanjq99/fnet/codec"
"github.com/fanjq99/glog"
)
var (
// Codecs are codecs supported by rpc. You can add customized codecs in Codecs.
Codecs = map[SerializeType]codec.Codec{
ProtoBuffer: &codec.PBCodec{},
JSON: &codec.JSONCodec{},
}
)
// SerializeType defines serialization type of Data.
type SerializeType byte
const (
// ProtoBuffer for payload.
ProtoBuffer SerializeType = iota
// JSON for payload.
JSON
)
// MessageType is message type of requests and resposnes.
type MessageType byte
const (
// Request is message type of request
Request MessageType = iota
// Response is message type of response
Response
)
// MessageStatusType is status of messages.
type MessageStatusType byte
const (
// Normal is normal requests and responses.
Normal MessageStatusType = iota
// Error indicates some errors occur.
Error
)
// Message tcp & webscoket share message struct
type Message struct {
MsgId uint32
Index uint32
SerializeType uint8
MessageType uint8
Status uint8
GateSessionId int64
Data []byte
}
func (m *Message) Encode() []byte {
buff := new(bytes.Buffer)
binary.Write(buff, binary.LittleEndian, m.MsgId)
binary.Write(buff, binary.LittleEndian, m.Index)
binary.Write(buff, binary.LittleEndian, m.SerializeType)
binary.Write(buff, binary.LittleEndian, m.MessageType)
binary.Write(buff, binary.LittleEndian, m.Status)
binary.Write(buff, binary.LittleEndian, m.GateSessionId)
binary.Write(buff, binary.LittleEndian, m.Data)
return buff.Bytes()
}
func (m *Message) Decode(buff []byte) error {
buf := bytes.NewBuffer(buff)
err := binary.Read(buf, binary.LittleEndian, &m.MsgId)
if err != nil {
glog.Errorln("decode MsgId err:", err)
return err
}
err = binary.Read(buf, binary.LittleEndian, &m.Index)
if err != nil {
glog.Errorln("decode Index err:", err)
return err
}
err = binary.Read(buf, binary.LittleEndian, &m.SerializeType)
if err != nil {
glog.Errorln("decode SerializeType err:", err)
return err
}
err = binary.Read(buf, binary.LittleEndian, &m.MessageType)
if err != nil {
glog.Errorln("decode MessageType err:", err)
return err
}
err = binary.Read(buf, binary.LittleEndian, &m.Status)
if err != nil {
glog.Errorln("decode Status err:", err)
return err
}
err = binary.Read(buf, binary.LittleEndian, &m.GateSessionId)
if err != nil {
glog.Errorln("decode GateSessionId err:", err)
return err
}
m.Data = buff[19:]
return nil
}