client.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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.tradeWriteChan != nil {
  81. r.tradeWriteChan <- buf
  82. } else {
  83. global.M2A_LOG.Info("WriteTradeWsBuf::tradeWriteChan == nil", zap.Any("LoginID", r.LoginID), zap.Any("SessionID", r.SessionID))
  84. }
  85. if r.wsTradeConn != nil {
  86. // r.tradeWriteChan <- buf
  87. } else {
  88. global.M2A_LOG.Info("WriteTradeWsBuf::wsTradeConn == nil", zap.Any("LoginID", r.LoginID), zap.Any("SessionID", r.SessionID))
  89. global.M2A_LOG.Info("当前所有Client----")
  90. for _, item := range Clients {
  91. global.M2A_LOG.Info("client",
  92. zap.Any("LoginID", item.LoginID),
  93. zap.Any("Group", item.Group), zap.Any("SessionID", item.SessionID),
  94. zap.Any("wsTradeConn", item.wsTradeConn), zap.Any("tradeWriteChan", item.tradeWriteChan),
  95. zap.Any("wsQuoteConn", item.wsQuoteConn), zap.Any("quoteWriteChan", item.quoteWriteChan))
  96. }
  97. global.M2A_LOG.Info("----------------")
  98. }
  99. return
  100. }
  101. // GetAsyncTask 获取目标异步任务
  102. // key:SessionId_FuncodeRsp
  103. func (r *Client) GetAsyncTask(key string) (asyncTask *AsyncTask) {
  104. r.mtx.RLock()
  105. defer func() {
  106. r.mtx.RUnlock()
  107. }()
  108. asyncTask, ok := r.asyncTasks[key]
  109. if ok {
  110. return asyncTask
  111. } else {
  112. return nil
  113. }
  114. }
  115. // SetAsyncTask 设置异步任务
  116. func (r *Client) SetAsyncTask(asyncTask *AsyncTask, key string) {
  117. r.mtx.Lock()
  118. defer func() {
  119. r.mtx.Unlock()
  120. }()
  121. if r.asyncTasks == nil {
  122. r.asyncTasks = make(map[string]*AsyncTask, 0)
  123. }
  124. delete(r.asyncTasks, key)
  125. r.asyncTasks[key] = asyncTask
  126. }
  127. // DeleteAsyncTask 删除异步任务
  128. func (r *Client) DeleteAsyncTask(key string) {
  129. r.mtx.Lock()
  130. defer func() {
  131. r.mtx.Unlock()
  132. }()
  133. delete(r.asyncTasks, key)
  134. }
  135. func (r *Client) GetAllAsyncTask() *map[string]*AsyncTask {
  136. return &r.asyncTasks
  137. }
  138. // **************** Quote WebSocket ****************
  139. func (r *Client) SetQuoteWebSocket(ws *websocket.Conn) (err error) {
  140. r.mtx.Lock()
  141. defer r.mtx.Unlock()
  142. // if r.wsQuoteConn != nil {
  143. // r.wsQuoteConn.Close()
  144. // }
  145. r.wsQuoteConn = ws
  146. r.quoteWriteChan = make(chan []byte, 100)
  147. // 开始读取客户端发送信息
  148. go r.readClientWsQuoteMessage()
  149. // 开始推送客户端信息循环
  150. go r.writeClientWsQuoteMessage()
  151. // r.wsQuoteConn.SetCloseHandler(func(code int, text string) error {
  152. // close(r.wsCloseChan)
  153. // return nil
  154. // })
  155. return
  156. }
  157. // readClientWsQuoteMessage 处理终端发过来的websocket数据
  158. // 注意: 阻塞式, 直到websocket关闭才退出
  159. func (r *Client) readClientWsQuoteMessage() {
  160. for {
  161. fmt.Println("readClientWsQuoteMessage start")
  162. // 40秒心跳超时
  163. r.wsQuoteConn.SetReadDeadline(time.Now().Add(40 * time.Second))
  164. mt, msg, err := r.wsQuoteConn.ReadMessage()
  165. if err != nil {
  166. fmt.Printf("readClientWsQuoteMessage: %v\n", err)
  167. return
  168. }
  169. switch mt {
  170. case websocket.PingMessage:
  171. _ = r.wsQuoteConn.WriteMessage(mt, msg)
  172. case websocket.CloseMessage:
  173. return
  174. case websocket.BinaryMessage:
  175. if err := r.clientToQuoteAgentMsg(msg); err != nil {
  176. return
  177. }
  178. case websocket.TextMessage:
  179. fmt.Println(string(msg))
  180. _ = r.wsQuoteConn.WriteMessage(mt, msg)
  181. }
  182. // FIXME: - 这里要判断是否有问题
  183. // select {
  184. // case <-r.wsCloseChan:
  185. // return
  186. // }
  187. }
  188. }
  189. // writeClientWsQuoteMessage 由于websocket非线程安全,
  190. // 所以由统一协程写入
  191. func (r *Client) writeClientWsQuoteMessage() {
  192. // defer r.close()
  193. // for {
  194. // select {
  195. // case buf := <-r.quoteWriteChan:
  196. // err := r.wsQuoteConn.WriteMessage(websocket.BinaryMessage, buf)
  197. // if err != nil {
  198. // return
  199. // }
  200. // case <-r.wsQuoteCloseChan: // 与终端连接关闭信息
  201. // return
  202. // }
  203. // }
  204. for {
  205. buf, ok := <-r.quoteWriteChan
  206. if !ok {
  207. // 通道已关闭
  208. return
  209. }
  210. err := r.wsQuoteConn.WriteMessage(websocket.BinaryMessage, buf)
  211. if err != nil {
  212. return
  213. }
  214. }
  215. }
  216. // clientToQuoteAgentMsg 处理客户端发上来的包
  217. func (r *Client) clientToQuoteAgentMsg(msg []byte) error {
  218. var p packet.MiQuotePacket
  219. err := p.UnPackHead(msg)
  220. if err != nil {
  221. // logger.Logger().Errorf("[%v c->s] invalid packet: %v", r.ProxyId, err)
  222. return err
  223. }
  224. // 长度15 是心跳包, 目前只允许客户端上行心跳包
  225. if p.Length == 15 {
  226. // logger.Logger().Debugf("%v [%v c->s] %s", r.ClientIP, r.ProxyId, p.HeaderInfo())
  227. // 将心跳发回给客户端
  228. err = r.wsQuoteConn.WriteMessage(websocket.BinaryMessage, msg)
  229. if err != nil {
  230. return err
  231. }
  232. }
  233. return nil
  234. }
  235. // **************** Trade WebSocket ****************
  236. func (r *Client) SetTradeWebSocket(ws *websocket.Conn) (err error) {
  237. r.mtx.Lock()
  238. defer r.mtx.Unlock()
  239. // if r.wsTradeConn != nil {
  240. // r.wsTradeConn.Close()
  241. // }
  242. r.wsTradeConn = ws
  243. r.tradeWriteChan = make(chan []byte, 100)
  244. r.wsTradeConn.SetCloseHandler(func(code int, text string) error {
  245. global.M2A_LOG.Info("交易长连发生断开", zap.Any("LoginID", r.LoginID), zap.Any("SessionID", r.SessionID), zap.Any("code", code), zap.Any("text", text))
  246. return nil
  247. })
  248. // 开始读取客户端发送信息
  249. go r.readClientWsTradeMessage()
  250. // 开始推送客户端信息循环
  251. go r.writeClientWsTradeMessage()
  252. global.M2A_LOG.Info("交易长连客户端接入", zap.Any("LoginID", r.LoginID), zap.Any("SessionID", r.SessionID))
  253. return
  254. }
  255. // readClientWsQuoteMessage 处理终端发过来的websocket数据
  256. // 注意: 阻塞式, 直到websocket关闭才退出
  257. func (r *Client) readClientWsTradeMessage() {
  258. for {
  259. fmt.Println("readClientWsTradeMessage start")
  260. // 40秒心跳超时
  261. r.wsTradeConn.SetReadDeadline(time.Now().Add(40 * time.Second))
  262. mt, msg, err := r.wsTradeConn.ReadMessage()
  263. if err != nil {
  264. global.M2A_LOG.Info("readClientWsTradeMessage::ReadMessage发生错误", zap.Any("err", err))
  265. return
  266. }
  267. switch mt {
  268. case websocket.PingMessage:
  269. if err = r.wsTradeConn.WriteMessage(mt, msg); err != nil {
  270. global.M2A_LOG.Info("readClientWsTradeMessage::PingMessage发生错误", zap.Any("err", err))
  271. }
  272. case websocket.CloseMessage:
  273. return
  274. case websocket.BinaryMessage:
  275. if err := r.clientToTradeAgentMsg(msg); err != nil {
  276. global.M2A_LOG.Info("readClientWsTradeMessage::BinaryMessage发生错误", zap.Any("err", err))
  277. return
  278. }
  279. case websocket.TextMessage:
  280. if err = r.wsTradeConn.WriteMessage(mt, msg); err != nil {
  281. global.M2A_LOG.Info("readClientWsTradeMessage::TextMessage发生错误", zap.Any("err", err))
  282. return
  283. }
  284. }
  285. }
  286. }
  287. // writeClientWsQuoteMessage 由于websocket非线程安全,
  288. // 所以由统一协程写入
  289. func (r *Client) writeClientWsTradeMessage() {
  290. for {
  291. buf, ok := <-r.tradeWriteChan
  292. if !ok {
  293. // 通道已关闭
  294. global.M2A_LOG.Info("writeClientWsTradeMessage 通道已关闭", zap.Any("LoginID", r.LoginID), zap.Any("SessionID", r.SessionID))
  295. return
  296. }
  297. err := r.wsTradeConn.WriteMessage(websocket.BinaryMessage, buf)
  298. if err != nil {
  299. global.M2A_LOG.Info("writeClientWsTradeMessage 向客户端发送信息时发生错误", zap.Any("LoginID", r.LoginID), zap.Any("SessionID", r.SessionID), zap.Any("err", err))
  300. return
  301. }
  302. }
  303. }
  304. // clientToTradeAgentMsg 处理客户端发上来的包
  305. func (r *Client) clientToTradeAgentMsg(msg []byte) error {
  306. var p packet.MiPacket
  307. err := p.UnPackHead(msg)
  308. if err != nil {
  309. // logger.Logger().Errorf("[%v c->s] invalid packet: %v", r.ProxyId, err)
  310. return err
  311. }
  312. // 长度24 是心跳包, 目前只允许客户端上行心跳包
  313. if p.Length == 24 {
  314. // logger.Logger().Debugf("%v [%v c->s] %s", r.ClientIP, r.ProxyId, p.HeaderInfo())
  315. // 将心跳发回给客户端
  316. err = r.wsTradeConn.WriteMessage(websocket.BinaryMessage, msg)
  317. if err != nil {
  318. return err
  319. }
  320. }
  321. return nil
  322. }
  323. // **************** RabbitMQ ****************
  324. // MQPacket 与总线交互的数据体
  325. type MQPacket struct {
  326. FunCode uint32 // 功能码
  327. SessionId uint32 // 数据包的sid
  328. Data *[]byte // 业务数据体
  329. }
  330. // AsyncTask 异步任务结构体
  331. type AsyncTask struct {
  332. PacketRsp chan MQPacket // 总线数据处理通道
  333. FuncodeRsp uint32 // 回复功能码
  334. SerialNumber uint32 // 通信流水号
  335. Own *Client
  336. IsEncrypted bool // 是否加密
  337. Rsp chan rsp.MQBodyRsp // 回调
  338. doClose sync.Once // 仅关闭通道一次
  339. }
  340. // Finish 完成
  341. func (r *AsyncTask) Finish() {
  342. r.doClose.Do(
  343. func() {
  344. close(r.Rsp)
  345. key := fmt.Sprintf("%v_%v_%v", r.Own.SessionID, r.FuncodeRsp, r.SerialNumber)
  346. r.Own.DeleteAsyncTask(key)
  347. })
  348. }
  349. type LoginRedis struct {
  350. LoginID string `json:"loginId" redis:"loginId"` // 登陆账号
  351. UserID string `json:"userId" redis:"userId"` // 用户ID
  352. SessionID string `json:"sessionId" redis:"sessionId"` // 终端sid
  353. Token string `json:"token" redis:"token"` // 令牌
  354. Group string `json:"group" redis:"group"` // 终端分组
  355. Addr string `json:"addr" redis:"addr"` // 客户端地址信息 // FIXME: 由于本服务改用短连,所以每次提交请交请求可能会不一样,后期可判断是否在中间件中进行拦截
  356. OldToken string `json:"-" redis:"-"` // 旧接入Token
  357. }
  358. // FromMap Map to Struct
  359. func (r *LoginRedis) FromMap(val map[string]interface{}) error {
  360. return mapstructure.Decode(val, r)
  361. }
  362. // ToMap Struct to Map
  363. func (r *LoginRedis) ToMap() (val map[string]interface{}, err error) {
  364. if marshalContent, err := json.Marshal(r); err != nil {
  365. return nil, err
  366. } else {
  367. d := json.NewDecoder(bytes.NewReader(marshalContent))
  368. d.UseNumber() // 设置将float64转为一个number
  369. if err := d.Decode(&val); err != nil {
  370. fmt.Println(err)
  371. } else {
  372. for k, v := range val {
  373. val[k] = v
  374. }
  375. }
  376. }
  377. return
  378. }