client.go 6.4 KB

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