c_websocket.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. request := Request1{
  48. Type: "request",
  49. CommandID: "heart",
  50. Parameter: nil,
  51. }
  52. requestJSON, err := json.Marshal(request)
  53. c_log.GlobalLogger.Info("requestJSON", requestJSON)
  54. if err != nil {
  55. c_log.GlobalLogger.Error("保持websocket连接活跃,解析requestJSON - 失败。", err)
  56. }
  57. for {
  58. select {
  59. case <-ticker.C:
  60. err := WsConn.WriteMessage(websocket.TextMessage, requestJSON)
  61. if err != nil {
  62. c_log.GlobalLogger.Error("保持websocket连接活跃,发送心跳请求 - 失败。", err)
  63. continue
  64. }
  65. _, msg, err := WsConn.ReadMessage()
  66. if err != nil {
  67. c_log.GlobalLogger.Error("保持websocket连接活跃,获取心跳响应 - 失败。", err)
  68. continue
  69. }
  70. c_log.GlobalLogger.Info("保持websocket连接活跃,发送心跳请求 - 成功。")
  71. // 将响应字节解码为JSON
  72. var responseMessage Response
  73. err = json.Unmarshal(msg, &responseMessage)
  74. if err != nil {
  75. c_log.GlobalLogger.Error("保持websocket连接活跃,解析心跳响应为json - 失败。", err)
  76. continue
  77. }
  78. c_log.GlobalLogger.Info("websocket responseMessage:", responseMessage)
  79. if responseMessage.Status != "" {
  80. c_log.GlobalLogger.Info("websocket发送心跳请求解析状态为", responseMessage.Status)
  81. }
  82. if responseMessage.ErrorCode != "" {
  83. c_log.GlobalLogger.Info("websocket发送心跳请求解析故障码为", responseMessage.ErrorCode)
  84. }
  85. if responseMessage.Status != "OK" {
  86. WsConn.Close()
  87. c_log.GlobalLogger.Info("重试连接websocket...")
  88. ConnectWebsocket() // 重新连接
  89. continue
  90. }
  91. }
  92. }
  93. }
  94. func ConnectWebsocket() {
  95. for {
  96. // 防止重复调用
  97. if reconnectionInProgress {
  98. return
  99. }
  100. reconnectionInProgress = true
  101. c_log.GlobalLogger.Info("初始化Websocket连接 - 开始。")
  102. serverURL := LocalConfig.Node.Ip + ":" + LocalConfig.LocalWebsocketPort
  103. path := "/"
  104. // 构建WebSocket连接URL
  105. u := url.URL{Scheme: "ws", Host: serverURL, Path: path}
  106. c_log.GlobalLogger.Info("URL:", u.String())
  107. // 创建一个Dialer实例,用于建立WebSocket连接
  108. dialer := websocket.Dialer{
  109. ReadBufferSize: 1024,
  110. WriteBufferSize: 1024,
  111. // 可选:设置超时等
  112. HandshakeTimeout: 5 * time.Minute,
  113. }
  114. // 建立WebSocket连接
  115. coon, _, err := dialer.Dial(u.String(), nil)
  116. if err != nil {
  117. fmt.Println("err:", err)
  118. c_log.GlobalLogger.Error("初始化Websocket连接 - 失败。")
  119. time.Sleep(5 * time.Second)
  120. reconnectionInProgress = false
  121. c_log.GlobalLogger.Info("重试连接websocket...")
  122. continue
  123. }
  124. WsConn = coon
  125. c_log.GlobalLogger.Info("初始化Websocket连接 - 成功。")
  126. // 连接成功,退出循环
  127. reconnectionInProgress = false
  128. break
  129. }
  130. }
  131. func InitWebsocketConfig() {
  132. ConnectWebsocket()
  133. // 保持连接活跃
  134. go keepAlive()
  135. }