WebSocket.go 4.3 KB

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