ws.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. package ws
  2. import (
  3. "encoding/json"
  4. "gadmin/utility/token"
  5. "net/http"
  6. "sync"
  7. "time"
  8. "github.com/gin-gonic/gin"
  9. "github.com/gorilla/websocket"
  10. "github.com/sirupsen/logrus"
  11. "github.com/spf13/cast"
  12. )
  13. type Msg struct {
  14. Type int64 `json:"type"` // 1 日志 2 用户查询
  15. Id int64 `json:"id"`
  16. Code int `json:"code"`
  17. Msg string `json:"msg"`
  18. CID string `json:"cid"` // clientId
  19. Extra map[string]interface{} `json:"extra,omitempty"`
  20. }
  21. func (msg *Msg) Bytes() []byte {
  22. data, _ := json.Marshal(msg)
  23. return data
  24. }
  25. type ReqMsg struct {
  26. Type int `json:"type"`
  27. Data string `json:"data"` //
  28. }
  29. type Client struct {
  30. Id int64
  31. c *websocket.Conn
  32. msgChan chan Msg
  33. msgReq chan ReqMsg
  34. lastHeart int64
  35. isBroken bool
  36. claims *token.UserClaims
  37. Lock sync.Mutex
  38. }
  39. func NewClient(id int64, conn *websocket.Conn) *Client {
  40. cli := &Client{
  41. Id: id,
  42. c: conn,
  43. msgChan: make(chan Msg, 100),
  44. msgReq: make(chan ReqMsg, 100),
  45. lastHeart: time.Now().Unix(),
  46. }
  47. return cli
  48. }
  49. func (client *Client) Handler() {
  50. go func() {
  51. for !client.isBroken {
  52. _, data, err := client.c.ReadMessage()
  53. if err != nil {
  54. logrus.Errorln("接收消息:", err.Error())
  55. client.isBroken = true
  56. break
  57. }
  58. var msg ReqMsg
  59. //logrus.Warn("接收到原始消息:", string(data))
  60. if err = json.Unmarshal(data, &msg); err != nil {
  61. logrus.Warn("Handler json.Unmarshal err:", err.Error())
  62. break
  63. }
  64. client.msgReq <- msg
  65. }
  66. }()
  67. for !client.isBroken {
  68. select {
  69. case msg, ok := <-client.msgReq: // 接收
  70. if ok {
  71. client.HandlerReqMsg(msg)
  72. }
  73. case msg, ok := <-client.msgChan: // 发送
  74. if ok {
  75. err := client.WriteResp(msg.Bytes())
  76. if err != nil {
  77. logrus.Error("写入:", err.Error())
  78. client.isBroken = true
  79. }
  80. }
  81. }
  82. }
  83. }
  84. var clients = make(map[int64]*Client)
  85. var lock sync.Mutex
  86. var BoardCast = make(chan Msg, 100) // 广播通道
  87. func NotifyBoardCast() {
  88. for {
  89. select {
  90. case msg, ok := <-BoardCast:
  91. logrus.Infof("new NotifyBoardCast :%+v", msg)
  92. if ok {
  93. for _, client := range clients {
  94. logrus.Info("client ", client.Id, " ,conn:", client.isBroken)
  95. if client.isBroken {
  96. client.Lock.Lock()
  97. client.c.Close()
  98. close(client.msgChan)
  99. close(client.msgReq)
  100. client.Lock.Unlock()
  101. lock.Lock()
  102. delete(clients, client.Id)
  103. lock.Unlock()
  104. continue
  105. }
  106. if msg.CID != "" {
  107. if client.Id == cast.ToInt64(msg.CID) {
  108. logrus.Infoln("NotifyBoardCast ", msg)
  109. client.msgChan <- msg
  110. break
  111. }
  112. } else {
  113. client.msgChan <- msg
  114. }
  115. }
  116. }
  117. default:
  118. time.Sleep(1 * time.Second)
  119. }
  120. }
  121. }
  122. var upgrader = websocket.Upgrader{
  123. // 解决跨域问题
  124. CheckOrigin: func(r *http.Request) bool {
  125. return true
  126. },
  127. } // use default options
  128. func Websocket(ctx *gin.Context) {
  129. c, err := upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
  130. if err != nil {
  131. logrus.Error("upgrade:", err)
  132. return
  133. }
  134. t := token.GetAuthorization(ctx)
  135. if t == "" {
  136. logrus.Error("没有登录")
  137. //return
  138. }
  139. claims, err := token.ParseToken(t)
  140. if err != nil {
  141. logrus.Error("token.ParseToken:", err.Error())
  142. //return
  143. }
  144. if claims == nil {
  145. claims = &token.UserClaims{}
  146. }
  147. now := time.Now().UnixNano() / 10e3
  148. client := &Client{
  149. Id: now,
  150. c: c,
  151. msgChan: make(chan Msg, 100),
  152. msgReq: make(chan ReqMsg, 100),
  153. lastHeart: time.Now().Unix(),
  154. claims: claims,
  155. }
  156. lock.Lock()
  157. clients[now] = client
  158. lock.Unlock()
  159. logrus.Infof("新用户接入ws, sid:%v, ip:%v, id:%v, userName:%v", client.Id, c.RemoteAddr(), client.claims.ID, client.claims.UserName)
  160. defer c.Close()
  161. client.Handler()
  162. }
  163. // GetClientsByAdminId 通过管理员ID查找在线的ws
  164. func GetClientsByAdminId(adminId int64) (checkedClients []*Client) {
  165. lock.Lock()
  166. defer lock.Unlock()
  167. for _, client := range clients {
  168. if client.claims.ID == adminId {
  169. checkedClients = append(checkedClients, client)
  170. }
  171. }
  172. return checkedClients
  173. }
  174. // SendToAdmin 发送消息给指定管理员
  175. func SendToAdmin(adminId int64, msg Msg) {
  176. checkedClients := GetClientsByAdminId(adminId)
  177. if len(checkedClients) == 0 {
  178. logrus.Warnf("当前管理员没有在线的ws admin_id:%v", adminId)
  179. return
  180. }
  181. for _, client := range checkedClients {
  182. logrus.Warnf("SendToAdmin id:%v, client.claims:%+v", client.Id, client.claims)
  183. client.WriteResp(msg.Bytes())
  184. }
  185. }