client.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. "github.com/gorilla/websocket"
  13. "github.com/mitchellh/mapstructure"
  14. )
  15. var Clients map[int]*Client // key:SessionID
  16. type Client struct {
  17. LoginRedis
  18. mtx sync.RWMutex
  19. curSerialNumber uint32 // 当前业务流水号
  20. asyncTasks map[string]*AsyncTask // key:SessionId_FuncodeRsp_SerialNumber
  21. wsConn *websocket.Conn // 终端WebSocket连接
  22. quoteSubs []request.QuoteGoods // 当前已订阅行情的商品
  23. ch chan interface{} // 接收实时行情订阅channel
  24. unSubscribe chan struct{} // 取消订阅信号
  25. writeChan chan []byte // 推送队列 QuoteServer -> Client
  26. wsCloseChan chan struct{} // 终端WebSocket连接关闭信号
  27. }
  28. // GetSerialNumber 获取可用流水号
  29. func (r *Client) GetSerialNumber() uint32 {
  30. r.mtx.Lock()
  31. defer func() {
  32. r.mtx.Unlock()
  33. }()
  34. r.curSerialNumber += 1
  35. return r.curSerialNumber
  36. }
  37. // SetQuoteSubs 设置商品行情订阅信息
  38. func (r *Client) SetQuoteSubs(req request.QuoteSubscribeReq) {
  39. r.mtx.Lock()
  40. defer r.mtx.Unlock()
  41. r.quoteSubs = req.QuoteGoodses
  42. if r.ch != nil {
  43. // r.unSubscribe <- struct{}{}
  44. global.M2A_Publish.Unsubscribe(publish.Topic_Quote, r.ch)
  45. }
  46. r.ch = global.M2A_Publish.Subscribe(publish.Topic_Quote)
  47. go func() {
  48. for {
  49. select {
  50. case msg, ok := <-r.ch:
  51. if !ok {
  52. return // 管道已关闭,退出循环
  53. }
  54. // 向客户端发送行情信息
  55. if p, ok := msg.(*packet.MiQuotePacket); ok {
  56. DispatchRealQuote(p, r)
  57. }
  58. case <-r.unSubscribe:
  59. // 取消订阅信息
  60. return
  61. }
  62. }
  63. }()
  64. }
  65. // GetQuoteSubs 获取已订阅行情商品信息列表
  66. func (r *Client) GetQuoteSubs() (quoteSubs []request.QuoteGoods) {
  67. r.mtx.Lock()
  68. defer r.mtx.Unlock()
  69. return r.quoteSubs
  70. }
  71. // WriteWsBuf 向客户端发送实时行情
  72. func (r *Client) WriteWsBuf(buf []byte) (err error) {
  73. r.writeChan <- buf
  74. return
  75. }
  76. // GetAsyncTask 获取目标异步任务
  77. // key:SessionId_FuncodeRsp
  78. func (r *Client) GetAsyncTask(key string) (asyncTask *AsyncTask) {
  79. r.mtx.RLock()
  80. defer func() {
  81. r.mtx.RUnlock()
  82. }()
  83. asyncTask, ok := r.asyncTasks[key]
  84. if ok {
  85. return asyncTask
  86. } else {
  87. return nil
  88. }
  89. }
  90. // SetAsyncTask 设置异步任务
  91. func (r *Client) SetAsyncTask(asyncTask *AsyncTask, key string) {
  92. r.mtx.Lock()
  93. defer func() {
  94. r.mtx.Unlock()
  95. }()
  96. if r.asyncTasks == nil {
  97. r.asyncTasks = make(map[string]*AsyncTask, 0)
  98. }
  99. delete(r.asyncTasks, key)
  100. r.asyncTasks[key] = asyncTask
  101. }
  102. // DeleteAsyncTask 删除异步任务
  103. func (r *Client) DeleteAsyncTask(key string) {
  104. r.mtx.Lock()
  105. defer func() {
  106. r.mtx.Unlock()
  107. }()
  108. delete(r.asyncTasks, key)
  109. }
  110. func (r *Client) GetAllAsyncTask() *map[string]*AsyncTask {
  111. return &r.asyncTasks
  112. }
  113. func (r *Client) SetWebSocket(ws *websocket.Conn) (err error) {
  114. r.mtx.Lock()
  115. defer r.mtx.Unlock()
  116. if r.wsConn != nil {
  117. r.wsConn.Close()
  118. }
  119. r.wsConn = ws
  120. // 开始读取客户端发送信息
  121. go r.readClientWsMessage()
  122. // 开始推送客户端信息循环
  123. r.writeChan = make(chan []byte, 100)
  124. go r.writeClientWsMessage()
  125. return
  126. }
  127. // readClientWsMessage 处理终端发过来的websocket数据
  128. // 注意: 阻塞式, 直到websocket关闭才退出
  129. func (r *Client) readClientWsMessage() {
  130. for {
  131. mt, msg, err := r.wsConn.ReadMessage()
  132. if err != nil {
  133. fmt.Println(err)
  134. break
  135. }
  136. switch mt {
  137. case websocket.PingMessage:
  138. _ = r.wsConn.WriteMessage(mt, msg)
  139. case websocket.CloseMessage:
  140. return
  141. case websocket.BinaryMessage:
  142. if err := r.clientToQuoteAgentMsg(msg); err != nil {
  143. return
  144. }
  145. case websocket.TextMessage:
  146. fmt.Println(string(msg))
  147. _ = r.wsConn.WriteMessage(mt, msg)
  148. }
  149. }
  150. }
  151. // writeClientWsMessage 由于websocket非线程安全,
  152. // 所以由统一协程写入
  153. func (r *Client) writeClientWsMessage() {
  154. // defer r.close()
  155. for {
  156. select {
  157. case buf := <-r.writeChan:
  158. err := r.wsConn.WriteMessage(websocket.BinaryMessage, buf)
  159. if err != nil {
  160. return
  161. }
  162. case <-r.wsCloseChan: // 与终端连接关闭信息
  163. return
  164. }
  165. }
  166. }
  167. // clientToQuoteAgentMsg 处理客户端发上来的包
  168. func (r *Client) clientToQuoteAgentMsg(msg []byte) error {
  169. var p packet.MiQuotePacket
  170. err := p.UnPackHead(msg)
  171. if err != nil {
  172. // logger.Logger().Errorf("[%v c->s] invalid packet: %v", r.ProxyId, err)
  173. return err
  174. }
  175. // 长度15 是心跳包, 目前只允许客户端上行心跳包
  176. if p.Length == 15 {
  177. // logger.Logger().Debugf("%v [%v c->s] %s", r.ClientIP, r.ProxyId, p.HeaderInfo())
  178. // 将心跳发回给客户端
  179. err = r.wsConn.WriteMessage(websocket.BinaryMessage, msg)
  180. if err != nil {
  181. return err
  182. }
  183. }
  184. return nil
  185. }
  186. // MQPacket 与总线交互的数据体
  187. type MQPacket struct {
  188. FunCode uint32 // 功能码
  189. SessionId uint32 // 数据包的sid
  190. Data *[]byte // 业务数据体
  191. }
  192. // AsyncTask 异步任务结构体
  193. type AsyncTask struct {
  194. PacketRsp chan MQPacket // 总线数据处理通道
  195. FuncodeRsp uint32 // 回复功能码
  196. SerialNumber uint32 // 通信流水号
  197. Own *Client
  198. IsEncrypted bool // 是否加密
  199. Rsp chan rsp.MQBodyRsp // 回调
  200. doClose sync.Once // 仅关闭通道一次
  201. }
  202. // Finish 完成
  203. func (r *AsyncTask) Finish() {
  204. r.doClose.Do(
  205. func() {
  206. close(r.Rsp)
  207. key := fmt.Sprintf("%v_%v_%v", r.Own.SessionID, r.FuncodeRsp, r.SerialNumber)
  208. r.Own.DeleteAsyncTask(key)
  209. })
  210. }
  211. type LoginRedis struct {
  212. LoginID string `json:"loginId" redis:"loginId"` // 登陆账号
  213. UserID string `json:"userId" redis:"userId"` // 用户ID
  214. SessionID string `json:"sessionId" redis:"sessionId"` // 终端sid
  215. Token string `json:"token" redis:"token"` // 令牌
  216. Group string `json:"group" redis:"group"` // 终端分组
  217. Addr string `json:"addr" redis:"addr"` // 客户端地址信息 // FIXME: 由于本服务改用短连,所以每次提交请交请求可能会不一样,后期可判断是否在中间件中进行拦截
  218. }
  219. // FromMap Map to Struct
  220. func (r *LoginRedis) FromMap(val map[string]interface{}) error {
  221. return mapstructure.Decode(val, r)
  222. }
  223. // ToMap Struct to Map
  224. func (r *LoginRedis) ToMap() (val map[string]interface{}, err error) {
  225. if marshalContent, err := json.Marshal(r); err != nil {
  226. return nil, err
  227. } else {
  228. d := json.NewDecoder(bytes.NewReader(marshalContent))
  229. d.UseNumber() // 设置将float64转为一个number
  230. if err := d.Decode(&val); err != nil {
  231. fmt.Println(err)
  232. } else {
  233. for k, v := range val {
  234. val[k] = v
  235. }
  236. }
  237. }
  238. return
  239. }