forked from llr104/LiFrame
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgateserver.go
234 lines (195 loc) · 5.37 KB
/
gateserver.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
package main
import (
"bytes"
"compress/gzip"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"github.com/llr104/LiFrame/core/liNet"
"github.com/llr104/LiFrame/proto"
"github.com/llr104/LiFrame/server/app"
"github.com/llr104/LiFrame/server/db"
"github.com/llr104/LiFrame/server/gate"
"github.com/llr104/LiFrame/utils"
"github.com/thinkoner/openssl"
"io/ioutil"
"net/http"
"os"
"runtime"
"strconv"
"strings"
)
var cid uint64 = 0
// http升级websocket协议的配置
var wsUpgrader = websocket.Upgrader{
// 允许所有CORS跨域请求
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func wsHandler(resp http.ResponseWriter, req *http.Request) {
// 应答客户端告知升级连接为websocket
wsSocket, err := wsUpgrader.Upgrade(resp, req, nil)
if err != nil {
return
}
cid++
app.MClientData.Inc()
wsConn := liNet.NewWsConnection(wsSocket, cid)
wsConn.SetOnMessage(handleWsMessage)
wsConn.SetOnClose(handleOnClose)
wsConn.Running()
}
func handleOnClose(wsConn *liNet.WsConnection) {
app.MClientData.Dec()
gate.MyGate.ConnectExit(wsConn)
utils.Log.Debug("handleOnClose wsCount:%d", app.MClientData.GetOnlineCnt())
}
func handleWsMessage(wsConn *liNet.WsConnection, req *liNet.WsMessageReq, rsp* liNet.WsMessageRsp) {
defer func() {
if err := recover(); err != nil {
message := fmt.Sprintf("%s", err)
var pcs [32]uintptr
n := runtime.Callers(3, pcs[:]) // skip first 3 caller
var str strings.Builder
str.WriteString(message + "\nTraceback:")
for _, pc := range pcs[:n] {
fn := runtime.FuncForPC(pc)
file, line := fn.FileLine(pc)
str.WriteString(fmt.Sprintf("\n\t%s:%d", file, line))
}
utils.Log.Emergency( str.String())
}
}()
if req.MsgType == websocket.TextMessage{
return
}
//解压包
b := new(bytes.Buffer)
binary.Write(b, binary.LittleEndian, req.Data)
r, err := gzip.NewReader(b)
if err != nil{
return
}
defer r.Close()
unzipData, err := ioutil.ReadAll(r)
if err!=nil{
return
}
encode, err := hex.DecodeString(string(unzipData))
if err != nil{
return
}
decode, _ := openssl.AesCBCDecrypt(encode, liNet.GateMessageKey, liNet.GateMessageKey, openssl.ZEROS_PADDING)
data := string(decode)
msgArr := strings.Split(data,"|")
if len(msgArr) == 4{
msgName := msgArr[0]
msgProxyId := msgArr[1]
seq := msgArr[2]
t, _ := strconv.Atoi(seq)
rsp.Seq = uint32(t)
body := msgArr[3]
if msgName == proto.GateHandshake{
if body == ""{
utils.Log.Info("不是断线重连")
handshakeId := gate.MyGate.ConnectEnter(wsConn)
rsp.Seq = req.Seq
rsp.Data = []byte(handshakeId)
rsp.FuncName = proto.GateHandshake
rsp.ProxyName = ""
}else{
utils.Log.Info("是断线重连")
handshakeId := gate.MyGate.Reconnect(wsConn, body)
rsp.Seq = req.Seq
rsp.Data = []byte(handshakeId)
rsp.FuncName = proto.GateHandshake
rsp.ProxyName = ""
}
return
}
_, err := wsConn.GetProperty("handshakeId")
if err != nil{
return
}
/*检测授权是否成功才转发消息*/
if msgName == proto.GateLoginServerReq{
ackInfo := proto.DistributeServerAck{}
if serverInfo, err:= app.ServerMgr.Distribute(proto.ServerTypeLogin); err != nil {
ackInfo.Code = proto.Code_Not_Server
utils.Log.Info("gateServer.LoginServerReq error:%s", err.Error())
}else{
ackInfo.Code = proto.Code_Success
ackInfo.ServerInfo = serverInfo
}
rsp.FuncName = proto.GateLoginServerReq
rsp.ProxyName = ""
rsp.Data, _ = json.Marshal(ackInfo)
rsp.Seq = req.Seq
}else if msgName == proto.GateExitProxy{
gate.MyGate.CloseProxy(wsConn, msgProxyId)
}else{
rsp.Seq = req.Seq
routerToTarget(wsConn, msgName, msgProxyId, body, rsp)
}
}
}
func routerToTarget(wsConn* liNet.WsConnection, msgName string, msgProxyId string, body string, rsp* liNet.WsMessageRsp){
isAuth := false
if proto.EnterLoginLoginReq == msgName || proto.EnterLoginRegisterReq == msgName{
isAuth = true
}else{
_, err := wsConn.GetProperty("session")
if err == nil {
isAuth = true
}
}
if isAuth {
isLive := false
proxyClient, err := gate.MyGate.ProxyClient(wsConn, msgProxyId, gate.Router)
if err == nil {
sendData := []byte(body)
if proxyClient.GetConn() != nil && proxyClient.GetConn().IsClose() == false{
isLive = true
proxyClient.GetConn().SetProperty("gateConn", wsConn)
proxyClient.GetConn().SetProperty("proxy", msgProxyId)
proxyClient.GetConn().RpcCall(msgName, sendData, gate.Router.Handle, gate.Router.HandleFail)
}
}else{
utils.Log.Warn(err.Error())
rsp.ProxyName = msgProxyId
rsp.FuncName = proto.ProxyError
rsp.Data = []byte(err.Error())
}
if isLive == false{
msg := fmt.Sprintf("%s ProxyClient not live", msgProxyId)
utils.Log.Warn(msg)
rsp.ProxyName = msgProxyId
rsp.FuncName = proto.ProxyError
rsp.Data = []byte(msg)
}
}else {
rsp.ProxyName = msgProxyId
rsp.FuncName = proto.AuthError
rsp.Data = []byte("")
}
}
func ShutDown(){
utils.Log.Info("ShutDown")
}
func main() {
if len(os.Args) > 1 {
cfgPath := os.Args[1]
utils.GlobalObject.Load(cfgPath)
}else{
utils.GlobalObject.Load("conf/gate.json")
}
db.Init()
go app.MasterClient(proto.ServerTypeGate)
app.SetShutDownFunc(ShutDown)
addr := fmt.Sprintf("%s:%d", utils.GlobalObject.AppConfig.Host, utils.GlobalObject.AppConfig.TcpPort)
http.HandleFunc("/", wsHandler)
http.ListenAndServe(addr, nil)
}