forked from viphxin/xingo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpcpack.go
114 lines (96 loc) · 2.36 KB
/
rpcpack.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
114
package cluster
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"github.com/viphxin/xingo/fnet"
"github.com/viphxin/xingo/iface"
"encoding/gob"
"github.com/viphxin/xingo/logger"
)
type RpcData struct {
MsgType RpcSignal `json:"msgtype"`
Key string `json:"key,omitempty"`
Target string `json:"target,omitempty"`
Args []interface{} `json:"args,omitempty"`
Result map[string]interface{} `json:"result,omitempty"`
}
type RpcPackege struct {
Len int32
Data []byte
}
type RpcRequest struct {
Fconn iface.IWriter
Rpcdata *RpcData
}
type RpcDataPack struct{}
func NewRpcDataPack() *RpcDataPack {
return &RpcDataPack{}
}
func (this *RpcDataPack) GetHeadLen() int32 {
return 4
}
func (this *RpcDataPack) Unpack(headdata []byte) (interface{}, error) {
headbuf := bytes.NewReader(headdata)
rp := &RpcPackege{}
// 读取Len
if err := binary.Read(headbuf, binary.LittleEndian, &rp.Len); err != nil {
return nil, err
}
// 封包太大
if rp.Len > fnet.MaxPacketSize {
return nil, errors.New("rpc packege too big!!!")
}
return rp, nil
}
//func (this *RpcDataPack) Pack(msgId uint32, pkg interface{}) (out []byte, err error) {
// outbuff := bytes.NewBuffer([]byte{})
// // 进行编码
// dataBytes := []byte{}
// data := pkg.(*RpcData)
// if data != nil {
// dataBytes, err = json.Marshal(data)
// }
//
// if err != nil {
// fmt.Println(fmt.Sprintf("json marshaling error: %s", err))
// }
// // 写Len
// if err = binary.Write(outbuff, binary.LittleEndian, uint32(len(dataBytes))); err != nil {
// return
// }
//
// //all pkg data
// if err = binary.Write(outbuff, binary.LittleEndian, dataBytes); err != nil {
// return
// }
//
// out = outbuff.Bytes()
// return
//
//}
func (this *RpcDataPack) Pack(msgId uint32, pkg interface{}) (out []byte, err error) {
outbuff := bytes.NewBuffer([]byte{})
// 进行编码
databuff := bytes.NewBuffer([]byte{})
data := pkg.(*RpcData)
if data != nil {
enc := gob.NewEncoder(databuff)
err = enc.Encode(data)
}
if err != nil {
logger.Error(fmt.Sprintf("rpcpack gob marshaling error: %s", err))
return
}
// 写Len
if err = binary.Write(outbuff, binary.LittleEndian, uint32(databuff.Len())); err != nil {
return
}
//all pkg data
if err = binary.Write(outbuff, binary.LittleEndian, databuff.Bytes()); err != nil {
return
}
out = outbuff.Bytes()
return
}