c_websocket.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package config
  2. import (
  3. "cicv-data-closedloop/common/config/c_log"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/gorilla/websocket"
  7. "net/url"
  8. "time"
  9. )
  10. var (
  11. WsConn *websocket.Conn
  12. reconnectionInProgress bool
  13. )
  14. // Request 结构体定义
  15. type Request struct {
  16. Type string `json:"type"`
  17. UUID string `json:"uuid"`
  18. CommandID string `json:"commandId"`
  19. Parameter interface{} `json:"parameter"`
  20. }
  21. // Request1 结构体定义
  22. type Request1 struct {
  23. Type string `json:"type"`
  24. CommandID string `json:"commandId"`
  25. Parameter interface{} `json:"parameter"`
  26. }
  27. // Response 结构体定义
  28. type Response struct {
  29. CommandID string `json:"commandId"`
  30. ErrorCode string `json:"errorCode"`
  31. Results map[string]string `json:"results"`
  32. Status string `json:"status"`
  33. Time int64 `json:"time"`
  34. Type string `json:"type"`
  35. UUID string `json:"uuid"`
  36. }
  37. // StatusMessage 状态消息 结构体定义
  38. type StatusMessage struct {
  39. Type string `json:"type"`
  40. Topic string `json:"topic"`
  41. Time int64 `json:"time"`
  42. Data interface{} `json:"data"`
  43. }
  44. func keepAlive() {
  45. ticker := time.NewTicker(30 * time.Second)
  46. defer ticker.Stop()
  47. for {
  48. select {
  49. case <-ticker.C:
  50. response, err := sendRequestAndAwaitResponse(WsConn)
  51. if err != nil || response == nil {
  52. continue
  53. }
  54. var responseMessage Response
  55. err = json.Unmarshal(response, &responseMessage)
  56. if err != nil {
  57. c_log.GlobalLogger.Error("保持websocket连接活跃,解析websocket响应 - 失败。", err)
  58. continue
  59. }
  60. c_log.GlobalLogger.Error("responseMessage", responseMessage)
  61. if responseMessage.Status != "OK" {
  62. WsConn.Close()
  63. c_log.GlobalLogger.Info("重试连接websocket...")
  64. ConnectWebsocket() // 重新连接
  65. continue
  66. }
  67. }
  68. }
  69. }
  70. func sendRequestAndAwaitResponse(ws *websocket.Conn) ([]byte, error) {
  71. request := Request1{
  72. Type: "request",
  73. CommandID: "heart",
  74. Parameter: nil,
  75. }
  76. requestJSON, err := json.Marshal(request)
  77. if err != nil {
  78. c_log.GlobalLogger.Error("保持websocket连接活跃,解析requestJSON - 失败。", err)
  79. return nil, err
  80. }
  81. err = ws.WriteMessage(websocket.TextMessage, requestJSON)
  82. if err != nil {
  83. c_log.GlobalLogger.Error("保持websocket连接活跃,发送心跳请求 - 失败。", err)
  84. return nil, err
  85. }
  86. c_log.GlobalLogger.Info("保持websocket连接活跃,发送心跳请求 - 成功。")
  87. // 使用channel等待响应
  88. responseChan := make(chan []byte)
  89. go handleMessages(ws, responseChan)
  90. select {
  91. case response := <-responseChan:
  92. c_log.GlobalLogger.Error("保持websocket连接活跃,等待心跳响应 - 成功。")
  93. return response, nil
  94. case <-time.After(30 * time.Second): // 设置超时时间
  95. c_log.GlobalLogger.Error("保持websocket连接活跃,等待心跳响应 - 超时。")
  96. return nil, fmt.Errorf("保持websocket连接活跃,等待心跳响应 - 超时。")
  97. }
  98. }
  99. func handleMessages(ws *websocket.Conn, responseChan chan<- []byte) {
  100. for {
  101. time.Sleep(100 * time.Millisecond)
  102. _, message, err := ws.ReadMessage()
  103. if err != nil {
  104. c_log.GlobalLogger.Error("保持websocket连接活跃,读取websocket消息 - 失败 ", err)
  105. return
  106. }
  107. var response Response
  108. if err := json.Unmarshal(message, &response); err == nil && response.Type == "response" {
  109. responseChan <- message
  110. close(responseChan)
  111. return
  112. }
  113. }
  114. }
  115. func ConnectWebsocket() {
  116. for {
  117. // 防止重复调用
  118. if reconnectionInProgress {
  119. return
  120. }
  121. reconnectionInProgress = true
  122. c_log.GlobalLogger.Info("初始化Websocket连接 - 开始。")
  123. serverURL := LocalConfig.Node.Ip + ":" + LocalConfig.LocalWebsocketPort
  124. path := "/"
  125. // 构建WebSocket连接URL
  126. u := url.URL{Scheme: "ws", Host: serverURL, Path: path}
  127. c_log.GlobalLogger.Info("URL:", u.String())
  128. // 创建一个Dialer实例,用于建立WebSocket连接
  129. dialer := websocket.Dialer{
  130. ReadBufferSize: 1024,
  131. WriteBufferSize: 1024,
  132. // 可选:设置超时等
  133. HandshakeTimeout: 5 * time.Minute,
  134. }
  135. // 建立WebSocket连接
  136. coon, _, err := dialer.Dial(u.String(), nil)
  137. if err != nil {
  138. fmt.Println("err:", err)
  139. c_log.GlobalLogger.Error("初始化Websocket连接 - 失败。")
  140. time.Sleep(5 * time.Second)
  141. reconnectionInProgress = false
  142. c_log.GlobalLogger.Info("重试连接websocket...")
  143. continue
  144. }
  145. WsConn = coon
  146. c_log.GlobalLogger.Info("初始化Websocket连接 - 成功。")
  147. // 连接成功,退出循环
  148. reconnectionInProgress = false
  149. break
  150. }
  151. }
  152. func InitWebsocketConfig() {
  153. ConnectWebsocket()
  154. // 保持连接活跃
  155. go keepAlive()
  156. }