client.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. package client
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "mtp20access/global"
  7. rsp "mtp20access/model/mq/response"
  8. "mtp20access/model/quote/request"
  9. "mtp20access/packet"
  10. "mtp20access/publish"
  11. "sync"
  12. "time"
  13. "github.com/gorilla/websocket"
  14. "github.com/mitchellh/mapstructure"
  15. "go.uber.org/zap"
  16. )
  17. var Clients map[int]*Client // key:SessionID
  18. type Client struct {
  19. LoginRedis
  20. // FIXME: - 这里是否需要定义多个锁?
  21. mtx sync.RWMutex
  22. curSerialNumber uint32 // 当前业务流水号
  23. asyncTasks map[string]*AsyncTask // key:SessionId_FuncodeRsp_SerialNumber
  24. wsQuoteConn *websocket.Conn // 终端行情WebSocket连接
  25. quoteWriteChan chan []byte // 推送队列 Access -> Client
  26. quoteChan chan interface{} // 接收实时行情订阅channel QuoteServer -> Access
  27. quoteSubs []request.QuoteGoods // 当前已订阅行情的商品
  28. // wsQuoteCloseChan chan struct{} // 终端WebSocket连接关闭信号
  29. wsTradeConn *websocket.Conn // 终端交易WebSocket连接
  30. tradeWriteChan chan []byte // 推送队列 Access -> Client
  31. // tradeChan chan interface{} // 接收交易通知channel RabbitMQ -> Access
  32. // wsTradeCloseChan chan struct{} // 终端WebSocket连接关闭信号
  33. }
  34. // GetSerialNumber 获取可用流水号
  35. func (r *Client) GetSerialNumber() uint32 {
  36. r.mtx.Lock()
  37. defer func() {
  38. r.mtx.Unlock()
  39. }()
  40. r.curSerialNumber += 1
  41. return r.curSerialNumber
  42. }
  43. // SetQuoteSubs 设置商品行情订阅信息
  44. func (r *Client) SetQuoteSubs(req request.QuoteSubscribeReq) {
  45. r.mtx.Lock()
  46. defer r.mtx.Unlock()
  47. r.quoteSubs = req.QuoteGoodses
  48. // 从订阅中心订阅行情通知
  49. if r.quoteChan != nil {
  50. global.M2A_Publish.Unsubscribe(publish.Topic_Quote, r.quoteChan)
  51. }
  52. r.quoteChan = global.M2A_Publish.Subscribe(publish.Topic_Quote)
  53. go func() {
  54. for {
  55. msg, ok := <-r.quoteChan
  56. if !ok {
  57. return // 管道已关闭,退出循环
  58. }
  59. // 向客户端发送行情信息
  60. if p, ok := msg.(*packet.MiQuotePacket); ok {
  61. DispatchRealQuote(p, r)
  62. }
  63. }
  64. }()
  65. }
  66. // GetQuoteSubs 获取已订阅行情商品信息列表
  67. func (r *Client) GetQuoteSubs() (quoteSubs []request.QuoteGoods) {
  68. r.mtx.Lock()
  69. defer r.mtx.Unlock()
  70. return r.quoteSubs
  71. }
  72. // WriteWsBuf 向客户端发送实时行情
  73. func (r *Client) WriteQuoteWsBuf(buf []byte) (err error) {
  74. if r.quoteWriteChan != nil {
  75. r.quoteWriteChan <- buf
  76. }
  77. return
  78. }
  79. func (r *Client) WriteTradeWsBuf(buf []byte) (err error) {
  80. if r.wsTradeConn != nil {
  81. r.tradeWriteChan <- buf
  82. } else {
  83. global.M2A_LOG.Info("WriteTradeWsBuf::wsTradeConn == nil", zap.Any("LoginID", r.LoginID), zap.Any("SessionID", r.SessionID))
  84. global.M2A_LOG.Info("当前所有Client----")
  85. for _, item := range Clients {
  86. global.M2A_LOG.Info("client", zap.Any("LoginID", item.LoginID), zap.Any("Group", item.Group), zap.Any("SessionID", item.SessionID))
  87. }
  88. global.M2A_LOG.Info("----------------")
  89. }
  90. return
  91. }
  92. // GetAsyncTask 获取目标异步任务
  93. // key:SessionId_FuncodeRsp
  94. func (r *Client) GetAsyncTask(key string) (asyncTask *AsyncTask) {
  95. r.mtx.RLock()
  96. defer func() {
  97. r.mtx.RUnlock()
  98. }()
  99. asyncTask, ok := r.asyncTasks[key]
  100. if ok {
  101. return asyncTask
  102. } else {
  103. return nil
  104. }
  105. }
  106. // SetAsyncTask 设置异步任务
  107. func (r *Client) SetAsyncTask(asyncTask *AsyncTask, key string) {
  108. r.mtx.Lock()
  109. defer func() {
  110. r.mtx.Unlock()
  111. }()
  112. if r.asyncTasks == nil {
  113. r.asyncTasks = make(map[string]*AsyncTask, 0)
  114. }
  115. delete(r.asyncTasks, key)
  116. r.asyncTasks[key] = asyncTask
  117. }
  118. // DeleteAsyncTask 删除异步任务
  119. func (r *Client) DeleteAsyncTask(key string) {
  120. r.mtx.Lock()
  121. defer func() {
  122. r.mtx.Unlock()
  123. }()
  124. delete(r.asyncTasks, key)
  125. }
  126. func (r *Client) GetAllAsyncTask() *map[string]*AsyncTask {
  127. return &r.asyncTasks
  128. }
  129. // **************** Quote WebSocket ****************
  130. func (r *Client) SetQuoteWebSocket(ws *websocket.Conn) (err error) {
  131. r.mtx.Lock()
  132. defer r.mtx.Unlock()
  133. // if r.wsQuoteConn != nil {
  134. // r.wsQuoteConn.Close()
  135. // }
  136. r.wsQuoteConn = ws
  137. r.quoteWriteChan = make(chan []byte, 100)
  138. // 开始读取客户端发送信息
  139. go r.readClientWsQuoteMessage()
  140. // 开始推送客户端信息循环
  141. go r.writeClientWsQuoteMessage()
  142. // r.wsQuoteConn.SetCloseHandler(func(code int, text string) error {
  143. // close(r.wsCloseChan)
  144. // return nil
  145. // })
  146. return
  147. }
  148. // readClientWsQuoteMessage 处理终端发过来的websocket数据
  149. // 注意: 阻塞式, 直到websocket关闭才退出
  150. func (r *Client) readClientWsQuoteMessage() {
  151. for {
  152. fmt.Println("readClientWsQuoteMessage start")
  153. // 40秒心跳超时
  154. r.wsQuoteConn.SetReadDeadline(time.Now().Add(40 * time.Second))
  155. mt, msg, err := r.wsQuoteConn.ReadMessage()
  156. if err != nil {
  157. fmt.Printf("readClientWsQuoteMessage: %v\n", err)
  158. return
  159. }
  160. switch mt {
  161. case websocket.PingMessage:
  162. _ = r.wsQuoteConn.WriteMessage(mt, msg)
  163. case websocket.CloseMessage:
  164. return
  165. case websocket.BinaryMessage:
  166. if err := r.clientToQuoteAgentMsg(msg); err != nil {
  167. return
  168. }
  169. case websocket.TextMessage:
  170. fmt.Println(string(msg))
  171. _ = r.wsQuoteConn.WriteMessage(mt, msg)
  172. }
  173. // FIXME: - 这里要判断是否有问题
  174. // select {
  175. // case <-r.wsCloseChan:
  176. // return
  177. // }
  178. }
  179. }
  180. // writeClientWsQuoteMessage 由于websocket非线程安全,
  181. // 所以由统一协程写入
  182. func (r *Client) writeClientWsQuoteMessage() {
  183. // defer r.close()
  184. // for {
  185. // select {
  186. // case buf := <-r.quoteWriteChan:
  187. // err := r.wsQuoteConn.WriteMessage(websocket.BinaryMessage, buf)
  188. // if err != nil {
  189. // return
  190. // }
  191. // case <-r.wsQuoteCloseChan: // 与终端连接关闭信息
  192. // return
  193. // }
  194. // }
  195. for {
  196. buf, ok := <-r.quoteWriteChan
  197. if !ok {
  198. // 通道已关闭
  199. return
  200. }
  201. err := r.wsQuoteConn.WriteMessage(websocket.BinaryMessage, buf)
  202. if err != nil {
  203. return
  204. }
  205. }
  206. }
  207. // clientToQuoteAgentMsg 处理客户端发上来的包
  208. func (r *Client) clientToQuoteAgentMsg(msg []byte) error {
  209. var p packet.MiQuotePacket
  210. err := p.UnPackHead(msg)
  211. if err != nil {
  212. // logger.Logger().Errorf("[%v c->s] invalid packet: %v", r.ProxyId, err)
  213. return err
  214. }
  215. // 长度15 是心跳包, 目前只允许客户端上行心跳包
  216. if p.Length == 15 {
  217. // logger.Logger().Debugf("%v [%v c->s] %s", r.ClientIP, r.ProxyId, p.HeaderInfo())
  218. // 将心跳发回给客户端
  219. err = r.wsQuoteConn.WriteMessage(websocket.BinaryMessage, msg)
  220. if err != nil {
  221. return err
  222. }
  223. }
  224. return nil
  225. }
  226. // **************** Trade WebSocket ****************
  227. func (r *Client) SetTradeWebSocket(ws *websocket.Conn) (err error) {
  228. r.mtx.Lock()
  229. defer r.mtx.Unlock()
  230. // if r.wsTradeConn != nil {
  231. // r.wsTradeConn.Close()
  232. // }
  233. r.wsTradeConn = ws
  234. r.tradeWriteChan = make(chan []byte, 100)
  235. // 开始读取客户端发送信息
  236. go r.readClientWsTradeMessage()
  237. // 开始推送客户端信息循环
  238. go r.writeClientWsTradeMessage()
  239. global.M2A_LOG.Info("交易长连客户端接入", zap.Any("LoginID", r.LoginID), zap.Any("SessionID", r.SessionID))
  240. return
  241. }
  242. // readClientWsQuoteMessage 处理终端发过来的websocket数据
  243. // 注意: 阻塞式, 直到websocket关闭才退出
  244. func (r *Client) readClientWsTradeMessage() {
  245. for {
  246. fmt.Println("readClientWsTradeMessage start")
  247. // 40秒心跳超时
  248. r.wsTradeConn.SetReadDeadline(time.Now().Add(40 * time.Second))
  249. mt, msg, err := r.wsTradeConn.ReadMessage()
  250. if err != nil {
  251. fmt.Printf("readClientWsTradeMessage: %v\n", err)
  252. return
  253. }
  254. switch mt {
  255. case websocket.PingMessage:
  256. _ = r.wsTradeConn.WriteMessage(mt, msg)
  257. case websocket.CloseMessage:
  258. return
  259. case websocket.BinaryMessage:
  260. if err := r.clientToTradeAgentMsg(msg); err != nil {
  261. return
  262. }
  263. case websocket.TextMessage:
  264. fmt.Println(string(msg))
  265. _ = r.wsTradeConn.WriteMessage(mt, msg)
  266. }
  267. }
  268. }
  269. // writeClientWsQuoteMessage 由于websocket非线程安全,
  270. // 所以由统一协程写入
  271. func (r *Client) writeClientWsTradeMessage() {
  272. for {
  273. buf, ok := <-r.tradeWriteChan
  274. if !ok {
  275. // 通道已关闭
  276. global.M2A_LOG.Info("writeClientWsTradeMessage 通道已关闭", zap.Any("LoginID", r.LoginID), zap.Any("SessionID", r.SessionID))
  277. return
  278. }
  279. err := r.wsTradeConn.WriteMessage(websocket.BinaryMessage, buf)
  280. if err != nil {
  281. global.M2A_LOG.Info("writeClientWsTradeMessage 向客户端发送信息时发生错误", zap.Any("LoginID", r.LoginID), zap.Any("SessionID", r.SessionID))
  282. return
  283. }
  284. }
  285. }
  286. // clientToTradeAgentMsg 处理客户端发上来的包
  287. func (r *Client) clientToTradeAgentMsg(msg []byte) error {
  288. var p packet.MiPacket
  289. err := p.UnPackHead(msg)
  290. if err != nil {
  291. // logger.Logger().Errorf("[%v c->s] invalid packet: %v", r.ProxyId, err)
  292. return err
  293. }
  294. // 长度24 是心跳包, 目前只允许客户端上行心跳包
  295. if p.Length == 24 {
  296. // logger.Logger().Debugf("%v [%v c->s] %s", r.ClientIP, r.ProxyId, p.HeaderInfo())
  297. // 将心跳发回给客户端
  298. err = r.wsTradeConn.WriteMessage(websocket.BinaryMessage, msg)
  299. if err != nil {
  300. return err
  301. }
  302. }
  303. return nil
  304. }
  305. // **************** RabbitMQ ****************
  306. // MQPacket 与总线交互的数据体
  307. type MQPacket struct {
  308. FunCode uint32 // 功能码
  309. SessionId uint32 // 数据包的sid
  310. Data *[]byte // 业务数据体
  311. }
  312. // AsyncTask 异步任务结构体
  313. type AsyncTask struct {
  314. PacketRsp chan MQPacket // 总线数据处理通道
  315. FuncodeRsp uint32 // 回复功能码
  316. SerialNumber uint32 // 通信流水号
  317. Own *Client
  318. IsEncrypted bool // 是否加密
  319. Rsp chan rsp.MQBodyRsp // 回调
  320. doClose sync.Once // 仅关闭通道一次
  321. }
  322. // Finish 完成
  323. func (r *AsyncTask) Finish() {
  324. r.doClose.Do(
  325. func() {
  326. close(r.Rsp)
  327. key := fmt.Sprintf("%v_%v_%v", r.Own.SessionID, r.FuncodeRsp, r.SerialNumber)
  328. r.Own.DeleteAsyncTask(key)
  329. })
  330. }
  331. type LoginRedis struct {
  332. LoginID string `json:"loginId" redis:"loginId"` // 登陆账号
  333. UserID string `json:"userId" redis:"userId"` // 用户ID
  334. SessionID string `json:"sessionId" redis:"sessionId"` // 终端sid
  335. Token string `json:"token" redis:"token"` // 令牌
  336. Group string `json:"group" redis:"group"` // 终端分组
  337. Addr string `json:"addr" redis:"addr"` // 客户端地址信息 // FIXME: 由于本服务改用短连,所以每次提交请交请求可能会不一样,后期可判断是否在中间件中进行拦截
  338. OldToken string `json:"-" redis:"-"` // 旧接入Token
  339. }
  340. // FromMap Map to Struct
  341. func (r *LoginRedis) FromMap(val map[string]interface{}) error {
  342. return mapstructure.Decode(val, r)
  343. }
  344. // ToMap Struct to Map
  345. func (r *LoginRedis) ToMap() (val map[string]interface{}, err error) {
  346. if marshalContent, err := json.Marshal(r); err != nil {
  347. return nil, err
  348. } else {
  349. d := json.NewDecoder(bytes.NewReader(marshalContent))
  350. d.UseNumber() // 设置将float64转为一个number
  351. if err := d.Decode(&val); err != nil {
  352. fmt.Println(err)
  353. } else {
  354. for k, v := range val {
  355. val[k] = v
  356. }
  357. }
  358. }
  359. return
  360. }