c_websocket.go 4.4 KB

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