c_websocket.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. }
  80. err = WsConn.WriteMessage(websocket.TextMessage, requestJSON)
  81. if err != nil {
  82. c_log.GlobalLogger.Error("保持websocket连接活跃,发送心跳请求 - 失败。", err)
  83. }
  84. c_log.GlobalLogger.Error("保持websocket连接活跃,发送心跳请求 - 成功。", err)
  85. // 使用channel等待响应
  86. responseChan := make(chan []byte)
  87. go handleMessages(ws, responseChan)
  88. select {
  89. case response := <-responseChan:
  90. c_log.GlobalLogger.Error("保持websocket连接活跃,等待心跳响应 - 成功。", err)
  91. return response, nil
  92. case <-time.After(30 * time.Second): // 设置超时时间
  93. return nil, fmt.Errorf("保持websocket连接活跃,等待心跳响应 - 超时。")
  94. }
  95. }
  96. func handleMessages(ws *websocket.Conn, responseChan chan<- []byte) {
  97. for {
  98. _, message, err := ws.ReadMessage()
  99. if err != nil {
  100. c_log.GlobalLogger.Error("保持websocket连接活跃,读取websocket消息失败", err)
  101. return
  102. }
  103. var response Response
  104. if err := json.Unmarshal(message, &response); err == nil && response.Type == "response" {
  105. responseChan <- message
  106. close(responseChan)
  107. return
  108. }
  109. }
  110. }
  111. func ConnectWebsocket() {
  112. for {
  113. // 防止重复调用
  114. if reconnectionInProgress {
  115. return
  116. }
  117. reconnectionInProgress = true
  118. c_log.GlobalLogger.Info("初始化Websocket连接 - 开始。")
  119. serverURL := LocalConfig.Node.Ip + ":" + LocalConfig.LocalWebsocketPort
  120. path := "/"
  121. // 构建WebSocket连接URL
  122. u := url.URL{Scheme: "ws", Host: serverURL, Path: path}
  123. c_log.GlobalLogger.Info("URL:", u.String())
  124. // 创建一个Dialer实例,用于建立WebSocket连接
  125. dialer := websocket.Dialer{
  126. ReadBufferSize: 1024,
  127. WriteBufferSize: 1024,
  128. // 可选:设置超时等
  129. HandshakeTimeout: 5 * time.Minute,
  130. }
  131. // 建立WebSocket连接
  132. coon, _, err := dialer.Dial(u.String(), nil)
  133. if err != nil {
  134. fmt.Println("err:", err)
  135. c_log.GlobalLogger.Error("初始化Websocket连接 - 失败。")
  136. time.Sleep(5 * time.Second)
  137. reconnectionInProgress = false
  138. c_log.GlobalLogger.Info("重试连接websocket...")
  139. continue
  140. }
  141. WsConn = coon
  142. c_log.GlobalLogger.Info("初始化Websocket连接 - 成功。")
  143. // 连接成功,退出循环
  144. reconnectionInProgress = false
  145. break
  146. }
  147. }
  148. func InitWebsocketConfig() {
  149. ConnectWebsocket()
  150. // 保持连接活跃
  151. go keepAlive()
  152. }