WebSocket.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. package WebSocket
  2. import (
  3. "Cold_Api/controllers/lib"
  4. "Cold_Api/logs"
  5. "Cold_Api/models/System"
  6. "container/list"
  7. "encoding/json"
  8. "fmt"
  9. beego "github.com/beego/beego/v2/server/web"
  10. "github.com/gorilla/websocket"
  11. "net/http"
  12. "sync"
  13. "time"
  14. )
  15. // WebSocketController handles WebSocket requests.
  16. type WebSocketController struct {
  17. beego.Controller
  18. }
  19. // 网关 -》服务端 json 通用模板
  20. type Event_w struct {
  21. Type int // JOIN, LEAVE, MESSAGE
  22. Timestamp int // Unix timestamp (secs)
  23. Content interface{}
  24. }
  25. type Ms_Project struct {
  26. Cmd string `json:"Cmd"`
  27. Sn string `json:"Sn"`
  28. }
  29. // Event archives.
  30. var archive = list.New()
  31. type WsConn struct {
  32. Conn *websocket.Conn
  33. Mux sync.RWMutex
  34. }
  35. var (
  36. countryCapitalMap map[string]WsConn /*创建集合 */
  37. )
  38. func Join_wc(user string, ws *websocket.Conn) bool {
  39. // 有先加入 给全部人发消息
  40. _, ok := countryCapitalMap[user] /*如果确定是真实的,则存在,否则不存在 */
  41. if ok {
  42. fmt.Println(user + " 重复")
  43. countryCapitalMap[user] = WsConn{Conn: ws}
  44. return true
  45. } else {
  46. fmt.Println(user + " 注册成功")
  47. countryCapitalMap[user] = WsConn{Conn: ws}
  48. return false
  49. }
  50. }
  51. func Leave(user string) {
  52. fmt.Println("注销:" + user)
  53. for k, _ := range lib.CountrySnMap {
  54. _, ok := lib.CountrySnMap[k].Uuid_list[user]
  55. if ok {
  56. fmt.Println("清楚成功 用户! KEY:",k," Uuid:",lib.CountrySnMap[k].Uuid_list[user])
  57. delete(lib.CountrySnMap[k].Uuid_list, user)
  58. if(len(lib.CountrySnMap[k].Uuid_list) == 0){
  59. fmt.Println("清楚成功 SN! KEY:",k)
  60. delete(lib.CountrySnMap, k)
  61. }
  62. }
  63. }
  64. delete(countryCapitalMap, user)
  65. }
  66. // This function handles all incoming chan messages.
  67. func chatroom() {
  68. countryCapitalMap = make(map[string]WsConn)
  69. }
  70. func init() {
  71. go chatroom()
  72. }
  73. // 连接 注册 Join method handles WebSocket requests for WebSocketController.
  74. func (this *WebSocketController) Join() {
  75. // 验证登录
  76. b_,admin_r := lib.Verification(this.Ctx.GetCookie("User_tokey"),this.GetString("User_tokey"))
  77. if(!b_){
  78. this.Redirect("/", 302)
  79. return
  80. }
  81. // Upgrade from http request to WebSocket.
  82. ws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)
  83. if _, ok := err.(websocket.HandshakeError); ok {
  84. http.Error(this.Ctx.ResponseWriter, "Not a websocket handshake", 400)
  85. return
  86. } else if err != nil {
  87. fmt.Println("无法设置WebSocket连接:", err)
  88. return
  89. }
  90. // Join chat room.
  91. is := Join_wc(admin_r.Admin_uuid, ws)
  92. if !is {
  93. defer Leave(admin_r.Admin_uuid) // 退后 会自动执行
  94. time.Sleep(3 * time.Second)
  95. for {
  96. _, p, err := ws.ReadMessage()
  97. if err != nil {
  98. return
  99. }
  100. fmt.Println("============= WebSocket JSON =============")
  101. fmt.Println(admin_r.Admin_uuid,"收到信息:",string(p))
  102. var Ms_project Ms_Project
  103. err = json.Unmarshal(p, &Ms_project)
  104. if err != nil {
  105. System.Add_Logs("WebSocket","JSON反序列化失败[Ms_Project]",string(p))
  106. fmt.Println("JSON反序列化失败[Ms_Project],err=",err)
  107. return
  108. }
  109. //fmt.Println("Cmd:", Ms_project.Cmd)
  110. fmt.Println("Sn:", Ms_project.Sn)
  111. //Parameter.Read_DeviceParameter(admin_r.Admin_uuid,Ms_project.Sn)
  112. _, ok := lib.CountrySnMap[Ms_project.Sn] /*如果确定是真实的,则存在,否则不存在 */
  113. if ok {
  114. }else {
  115. fmt.Println("CountrySnMap 没有,新建",Ms_project.Sn)
  116. lib.CountrySnMap[Ms_project.Sn] = lib.Cl_{
  117. Uuid_list: make(map[string]string) ,
  118. }
  119. }
  120. // 是否 有相同 用户
  121. _, ok = lib.CountrySnMap[Ms_project.Sn].Uuid_list[admin_r.Admin_uuid]
  122. if ok {
  123. fmt.Println("用户重复 ",admin_r.Admin_uuid)
  124. data, _ := json.Marshal(lib.JSONS{Code: 201, Msg: "用户重复!",Data: admin_r.Admin_uuid})
  125. Send_WebSocket(admin_r.Admin_uuid,string(data))
  126. }else {
  127. fmt.Println("用户新建 ",admin_r.Admin_uuid)
  128. lib.CountrySnMap[Ms_project.Sn].Uuid_list[admin_r.Admin_uuid] = admin_r.Admin_uuid
  129. data, _ := json.Marshal(lib.JSONS{Code: 200, Msg: "ok!",Data: admin_r.Admin_uuid})
  130. Send_WebSocket(admin_r.Admin_uuid,string(data))
  131. lib.CountryRead_DeviceParameterSnMap[Ms_project.Sn] = ""
  132. }
  133. }
  134. }else {
  135. this.Redirect("/", 302)
  136. return
  137. }
  138. }
  139. /// ------------- ---------------------------------------------
  140. func Send_WebSocket(Admin_uuid string,T_json string) {
  141. defer func() {
  142. if err := recover(); err != nil {
  143. fmt.Println(err)
  144. logs.Println("Send_WebSocket ok err:!",err)
  145. System.Add_Logs("WebSocket", "Send_WebSocket Err", Admin_uuid+T_json)
  146. }
  147. }()
  148. ws, ok := countryCapitalMap[Admin_uuid] /*如果确定是真实的,则存在,否则不存在 */
  149. if ok && ws.Conn != nil {
  150. ws.Mux.Lock()
  151. if ws.Conn.WriteMessage(websocket.TextMessage, []byte(T_json)) != nil {
  152. println("ok!")
  153. }
  154. ws.Mux.Unlock()
  155. }
  156. }