-
Notifications
You must be signed in to change notification settings - Fork 205
/
clientconn.go
256 lines (224 loc) · 5.68 KB
/
clientconn.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package net
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/forgoer/openssl"
"github.com/goinggo/mapstructure"
"github.com/gorilla/websocket"
"github.com/llr104/slgserver/constant"
"github.com/llr104/slgserver/log"
"github.com/llr104/slgserver/util"
"go.uber.org/zap"
)
// 客户端连接
type ClientConn struct {
wsSocket *websocket.Conn // 底层websocket
isClosed bool
Seq int64
onClose func(conn*ClientConn)
onPush func(conn*ClientConn, body*RspBody)
//链接属性
property map[string]interface{}
//保护链接属性修改的锁
propertyLock sync.RWMutex
syncCtxs map[int64]*syncCtx
syncLock sync.RWMutex
handshakeChan chan bool
handshake bool
}
func NewClientConn(wsSocket *websocket.Conn) *ClientConn {
conn := &ClientConn{
wsSocket: wsSocket,
isClosed: false,
property: make(map[string]interface{}),
Seq: 0,
syncCtxs: make(map[int64]*syncCtx),
handshakeChan: make(chan bool),
}
return conn
}
func (this *ClientConn) waitHandshake() bool{
if this.handshake == false{
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
select {
case _ = <-this.handshakeChan:{
log.DefaultLog.Info("recv handshakeChan")
return true
}
case <-ctx.Done():{
log.DefaultLog.Info("recv handshakeChan timeout")
return false
}
}
}
return true
}
func (this *ClientConn) Start() bool{
this.handshake = false
go this.wsReadLoop()
return this.waitHandshake()
}
func (this *ClientConn) Addr() string {
return this.wsSocket.RemoteAddr().String()
}
func (this *ClientConn) Push(name string, data interface{}) {
rsp := &WsMsgRsp{Body: &RspBody{Name: name, Msg: data, Seq: 0}}
this.write(rsp.Body)
}
func (this *ClientConn) Send(name string, data interface{}) *RspBody{
this.syncLock.Lock()
sync := newSyncCtx()
this.Seq += 1
seq := this.Seq
req := ReqBody{Name: name, Msg: data, Seq: seq}
this.syncCtxs[this.Seq] = sync
this.syncLock.Unlock()
rsp := &RspBody{Code: constant.OK, Name: name, Seq: seq }
err := this.write(req)
if err != nil{
sync.cancel()
}else{
r := sync.wait()
if r == nil{
rsp.Code = constant.ProxyConnectError
}else{
rsp = r
}
}
this.syncLock.Lock()
delete(this.syncCtxs, seq)
this.syncLock.Unlock()
return rsp
}
func (this *ClientConn) wsReadLoop() {
defer func() {
if err := recover(); err != nil {
e := fmt.Sprintf("%v", err)
log.DefaultLog.Error("wsReadLoop error", zap.String("err", e))
this.Close()
}
}()
for {
// 读一个message
_, data, err := this.wsSocket.ReadMessage()
if err != nil {
break
}
data, err = util.UnZip(data)
if err != nil {
log.DefaultLog.Error("wsReadLoop UnZip error", zap.Error(err))
continue
}
//需要检测是否有加密
body := &RspBody{}
if secretKey, err := this.GetProperty("secretKey"); err == nil {
key := secretKey.(string)
d, err := util.AesCBCDecrypt(data, []byte(key), []byte(key), openssl.ZEROS_PADDING)
if err != nil {
log.DefaultLog.Error("AesDecrypt error", zap.Error(err))
}else{
data = d
}
}
if err := util.Unmarshal(data, body); err == nil {
if body.Seq == 0 {
if body.Name == HandshakeMsg{
h := Handshake{}
mapstructure.Decode(body.Msg, &h)
log.DefaultLog.Info("client 收到握手协议", zap.String("data", string(data)))
if h.Key != ""{
this.SetProperty("secretKey", h.Key)
}else{
this.RemoveProperty("secretKey")
}
this.handshake = true
this.handshakeChan <- true
}else{
//推送,需要推送到指定的代理连接
if this.onPush != nil{
this.onPush(this, body)
}else{
log.DefaultLog.Warn("clientconn not deal push")
}
}
}else{
this.syncLock.RLock()
s, ok := this.syncCtxs[body.Seq]
this.syncLock.RUnlock()
if ok {
s.outChan <- body
}else{
log.DefaultLog.Warn("seq not found sync",
zap.Int64("seq", body.Seq),
zap.String("msgName", body.Name))
}
}
}else{
log.DefaultLog.Error("wsReadLoop Unmarshal error", zap.Error(err))
}
}
this.Close()
}
func (this *ClientConn) write(msg interface{}) error{
data, err := util.Marshal(msg)
if err == nil {
if secretKey, err:= this.GetProperty("secretKey"); err == nil {
key := secretKey.(string)
log.DefaultLog.Info("secretKey", zap.String("secretKey", key))
data, _ = util.AesCBCEncrypt(data, []byte(key), []byte(key), openssl.ZEROS_PADDING)
}
}else {
log.DefaultLog.Error("wsWriteLoop Marshal body error", zap.Error(err))
return err
}
if data, err := util.Zip(data); err == nil{
if err := this.wsSocket.WriteMessage(websocket.BinaryMessage, data); err != nil {
this.Close()
return err
}
}else{
return err
}
return nil
}
func (this *ClientConn) Close() {
this.wsSocket.Close()
if !this.isClosed {
this.isClosed = true
if this.onClose != nil{
this.onClose(this)
}
}
}
//设置链接属性
func (this *ClientConn) SetProperty(key string, value interface{}) {
this.propertyLock.Lock()
defer this.propertyLock.Unlock()
this.property[key] = value
}
//获取链接属性
func (this *ClientConn) GetProperty(key string) (interface{}, error) {
this.propertyLock.RLock()
defer this.propertyLock.RUnlock()
if value, ok := this.property[key]; ok {
return value, nil
} else {
return nil, errors.New("no property found")
}
}
//移除链接属性
func (this *ClientConn) RemoveProperty(key string) {
this.propertyLock.Lock()
defer this.propertyLock.Unlock()
delete(this.property, key)
}
func (this *ClientConn) SetOnClose(hookFunc func (*ClientConn)) {
this.onClose = hookFunc
}
func (this *ClientConn) SetOnPush(hookFunc func (*ClientConn, *RspBody)) {
this.onPush = hookFunc
}