c_websocket.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package config
  2. import (
  3. "cicv-data-closedloop/common/config/c_log"
  4. "fmt"
  5. "github.com/gorilla/websocket"
  6. "net/url"
  7. "time"
  8. )
  9. var (
  10. WsConn *websocket.Conn
  11. reconnectionInProgress bool
  12. )
  13. // Request 结构体定义
  14. type Request struct {
  15. Type string `json:"type"`
  16. UUID string `json:"uuid"`
  17. CommandID string `json:"commandId"`
  18. Parameter interface{} `json:"parameter"`
  19. }
  20. // Response 结构体定义
  21. type Response struct {
  22. CommandID string `json:"commandId"`
  23. ErrorCode string `json:"errorCode"`
  24. Results map[string]string `json:"results"`
  25. Status string `json:"status"`
  26. Time int64 `json:"time"`
  27. Type string `json:"type"`
  28. UUID string `json:"uuid"`
  29. }
  30. // 状态消息 结构体定义
  31. type StatusMessage struct {
  32. Type string `json:"type"`
  33. Topic string `json:"topic"`
  34. Time int64 `json:"time"`
  35. Data interface{} `json:"data"`
  36. }
  37. func keepAlive() {
  38. ticker := time.NewTicker(30 * time.Second)
  39. defer ticker.Stop()
  40. for {
  41. select {
  42. case <-ticker.C:
  43. if err := WsConn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
  44. c_log.GlobalLogger.Error("保持websocket连接活跃,发送ping - 失败。", err)
  45. WsConn.Close()
  46. c_log.GlobalLogger.Info("重试连接websocket...")
  47. InitWebsocketConfig() // 重新连接
  48. return
  49. }
  50. }
  51. }
  52. }
  53. func InitWebsocketConfig() {
  54. for {
  55. // 防止重复调用
  56. if reconnectionInProgress {
  57. return
  58. }
  59. reconnectionInProgress = true
  60. c_log.GlobalLogger.Info("初始化Websocket连接 - 开始。")
  61. serverURL := LocalConfig.Node.Ip + ":" + LocalConfig.LocalWebsocketPort
  62. path := "/"
  63. // 构建WebSocket连接URL
  64. u := url.URL{Scheme: "ws", Host: serverURL, Path: path}
  65. c_log.GlobalLogger.Info("URL:", u.String())
  66. // 创建一个Dialer实例,用于建立WebSocket连接
  67. dialer := websocket.Dialer{
  68. ReadBufferSize: 1024,
  69. WriteBufferSize: 1024,
  70. // 可选:设置超时等
  71. HandshakeTimeout: 5 * time.Second,
  72. }
  73. // 建立WebSocket连接
  74. coon, _, err := dialer.Dial(u.String(), nil)
  75. if err != nil {
  76. fmt.Println("err:", err)
  77. c_log.GlobalLogger.Error("初始化Websocket连接 - 失败。")
  78. time.Sleep(5 * time.Second)
  79. reconnectionInProgress = false
  80. c_log.GlobalLogger.Info("重试连接websocket...")
  81. continue
  82. }
  83. WsConn = coon
  84. c_log.GlobalLogger.Info("初始化Websocket连接 - 成功。")
  85. // 保持连接活跃
  86. //go keepAlive()
  87. // 连接成功,退出循环
  88. reconnectionInProgress = false
  89. break
  90. }
  91. }