-
Notifications
You must be signed in to change notification settings - Fork 7
/
connack.go
executable file
·93 lines (80 loc) · 2.42 KB
/
connack.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
package wkproto
import (
"fmt"
"github.com/pkg/errors"
)
// ConnackPacket 连接回执包
type ConnackPacket struct {
Framer
ServerVersion uint8 // 服务端版本
ServerKey string // 服务端的DH公钥
Salt string // salt
TimeDiff int64 // 客户端时间与服务器的差值,单位毫秒。
ReasonCode ReasonCode // 原因码
NodeId uint64 // 节点Id
}
// GetFrameType 获取包类型
func (c ConnackPacket) GetFrameType() FrameType {
return CONNACK
}
func (c ConnackPacket) String() string {
return fmt.Sprintf("TimeDiff: %d ReasonCode:%s", c.TimeDiff, c.ReasonCode.String())
}
func encodeConnack(connack *ConnackPacket, enc *Encoder, version uint8) error {
if connack.GetHasServerVersion() {
enc.WriteUint8(connack.ServerVersion)
}
enc.WriteInt64(connack.TimeDiff)
_ = enc.WriteByte(connack.ReasonCode.Byte())
enc.WriteString(connack.ServerKey)
enc.WriteString(connack.Salt)
if version >= 4 {
enc.WriteUint64(connack.NodeId)
}
return nil
}
func encodeConnackSize(packet *ConnackPacket, version uint8) int {
size := 0
if packet.GetHasServerVersion() {
size += VersionByteSize
}
size += TimeDiffByteSize
size += ReasonCodeByteSize
size += (len(packet.ServerKey) + StringFixLenByteSize)
size += (len(packet.Salt) + StringFixLenByteSize)
if version >= 4 {
size += NodeIdByteSize
}
return size
}
func decodeConnack(frame Frame, data []byte, version uint8) (Frame, error) {
dec := NewDecoder(data)
connackPacket := &ConnackPacket{}
connackPacket.Framer = frame.(Framer)
var err error
if frame.GetHasServerVersion() {
if connackPacket.ServerVersion, err = dec.Uint8(); err != nil {
return nil, errors.Wrap(err, "解码version失败!")
}
}
if connackPacket.TimeDiff, err = dec.Int64(); err != nil {
return nil, errors.Wrap(err, "解码TimeDiff失败!")
}
var reasonCode uint8
if reasonCode, err = dec.Uint8(); err != nil {
return nil, errors.Wrap(err, "解码ReasonCode失败!")
}
connackPacket.ReasonCode = ReasonCode(reasonCode)
if connackPacket.ServerKey, err = dec.String(); err != nil {
return nil, errors.Wrap(err, "解码ServerKey失败!")
}
if connackPacket.Salt, err = dec.String(); err != nil {
return nil, errors.Wrap(err, "解码Salt失败!")
}
if version >= 4 {
if connackPacket.NodeId, err = dec.Uint64(); err != nil {
return nil, errors.Wrap(err, "解码NodeId失败!")
}
}
return connackPacket, nil
}