client.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. // 开始读取客户端发送信息
  245. go r.readClientWsTradeMessage()
  246. // 开始推送客户端信息循环
  247. go r.writeClientWsTradeMessage()
  248. global.M2A_LOG.Info("交易长连客户端接入", zap.Any("LoginID", r.LoginID), zap.Any("SessionID", r.SessionID))
  249. return
  250. }
  251. // readClientWsQuoteMessage 处理终端发过来的websocket数据
  252. // 注意: 阻塞式, 直到websocket关闭才退出
  253. func (r *Client) readClientWsTradeMessage() {
  254. for {
  255. fmt.Println("readClientWsTradeMessage start")
  256. // 40秒心跳超时
  257. r.wsTradeConn.SetReadDeadline(time.Now().Add(40 * time.Second))
  258. mt, msg, err := r.wsTradeConn.ReadMessage()
  259. if err != nil {
  260. global.M2A_LOG.Info("readClientWsTradeMessage::ReadMessage发生错误", zap.Any("err", err))
  261. return
  262. }
  263. switch mt {
  264. case websocket.PingMessage:
  265. if err = r.wsTradeConn.WriteMessage(mt, msg); err != nil {
  266. global.M2A_LOG.Info("readClientWsTradeMessage::PingMessage发生错误", zap.Any("err", err))
  267. }
  268. case websocket.CloseMessage:
  269. return
  270. case websocket.BinaryMessage:
  271. if err := r.clientToTradeAgentMsg(msg); err != nil {
  272. global.M2A_LOG.Info("readClientWsTradeMessage::BinaryMessage发生错误", zap.Any("err", err))
  273. return
  274. }
  275. case websocket.TextMessage:
  276. if err = r.wsTradeConn.WriteMessage(mt, msg); err != nil {
  277. global.M2A_LOG.Info("readClientWsTradeMessage::TextMessage发生错误", zap.Any("err", err))
  278. return
  279. }
  280. }
  281. }
  282. }
  283. // writeClientWsQuoteMessage 由于websocket非线程安全,
  284. // 所以由统一协程写入
  285. func (r *Client) writeClientWsTradeMessage() {
  286. for {
  287. buf, ok := <-r.tradeWriteChan
  288. if !ok {
  289. // 通道已关闭
  290. global.M2A_LOG.Info("writeClientWsTradeMessage 通道已关闭", zap.Any("LoginID", r.LoginID), zap.Any("SessionID", r.SessionID))
  291. return
  292. }
  293. err := r.wsTradeConn.WriteMessage(websocket.BinaryMessage, buf)
  294. if err != nil {
  295. global.M2A_LOG.Info("writeClientWsTradeMessage 向客户端发送信息时发生错误", zap.Any("LoginID", r.LoginID), zap.Any("SessionID", r.SessionID), zap.Any("err", err))
  296. return
  297. }
  298. }
  299. }
  300. // clientToTradeAgentMsg 处理客户端发上来的包
  301. func (r *Client) clientToTradeAgentMsg(msg []byte) error {
  302. var p packet.MiPacket
  303. err := p.UnPackHead(msg)
  304. if err != nil {
  305. // logger.Logger().Errorf("[%v c->s] invalid packet: %v", r.ProxyId, err)
  306. return err
  307. }
  308. // 长度24 是心跳包, 目前只允许客户端上行心跳包
  309. if p.Length == 24 {
  310. // logger.Logger().Debugf("%v [%v c->s] %s", r.ClientIP, r.ProxyId, p.HeaderInfo())
  311. // 将心跳发回给客户端
  312. err = r.wsTradeConn.WriteMessage(websocket.BinaryMessage, msg)
  313. if err != nil {
  314. return err
  315. }
  316. }
  317. return nil
  318. }
  319. // **************** RabbitMQ ****************
  320. // MQPacket 与总线交互的数据体
  321. type MQPacket struct {
  322. FunCode uint32 // 功能码
  323. SessionId uint32 // 数据包的sid
  324. Data *[]byte // 业务数据体
  325. }
  326. // AsyncTask 异步任务结构体
  327. type AsyncTask struct {
  328. PacketRsp chan MQPacket // 总线数据处理通道
  329. FuncodeRsp uint32 // 回复功能码
  330. SerialNumber uint32 // 通信流水号
  331. Own *Client
  332. IsEncrypted bool // 是否加密
  333. Rsp chan rsp.MQBodyRsp // 回调
  334. doClose sync.Once // 仅关闭通道一次
  335. }
  336. // Finish 完成
  337. func (r *AsyncTask) Finish() {
  338. r.doClose.Do(
  339. func() {
  340. close(r.Rsp)
  341. key := fmt.Sprintf("%v_%v_%v", r.Own.SessionID, r.FuncodeRsp, r.SerialNumber)
  342. r.Own.DeleteAsyncTask(key)
  343. })
  344. }
  345. type LoginRedis struct {
  346. LoginID string `json:"loginId" redis:"loginId"` // 登陆账号
  347. UserID string `json:"userId" redis:"userId"` // 用户ID
  348. SessionID string `json:"sessionId" redis:"sessionId"` // 终端sid
  349. Token string `json:"token" redis:"token"` // 令牌
  350. Group string `json:"group" redis:"group"` // 终端分组
  351. Addr string `json:"addr" redis:"addr"` // 客户端地址信息 // FIXME: 由于本服务改用短连,所以每次提交请交请求可能会不一样,后期可判断是否在中间件中进行拦截
  352. OldToken string `json:"-" redis:"-"` // 旧接入Token
  353. }
  354. // FromMap Map to Struct
  355. func (r *LoginRedis) FromMap(val map[string]interface{}) error {
  356. return mapstructure.Decode(val, r)
  357. }
  358. // ToMap Struct to Map
  359. func (r *LoginRedis) ToMap() (val map[string]interface{}, err error) {
  360. if marshalContent, err := json.Marshal(r); err != nil {
  361. return nil, err
  362. } else {
  363. d := json.NewDecoder(bytes.NewReader(marshalContent))
  364. d.UseNumber() // 设置将float64转为一个number
  365. if err := d.Decode(&val); err != nil {
  366. fmt.Println(err)
  367. } else {
  368. for k, v := range val {
  369. val[k] = v
  370. }
  371. }
  372. }
  373. return
  374. }