index.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package stc
  2. import (
  3. "fmt"
  4. "net"
  5. "pbx-api-gin/internal/app/stc/broadcast"
  6. msgdata "pbx-api-gin/internal/app/stc/data"
  7. "sync"
  8. "syscall"
  9. "time"
  10. )
  11. func StartStcConnection(ServerAddr string, Port int) {
  12. //var conn net.Conn
  13. var wg sync.WaitGroup
  14. for {
  15. // 尝试建立连接
  16. conn, err := CreateConnection(ServerAddr, Port)
  17. if err != nil {
  18. fmt.Printf("连接失败 %s:%d,将在5秒后重试...\n", ServerAddr, Port)
  19. time.Sleep(5 * time.Second)
  20. continue
  21. }
  22. fmt.Printf("成功连接到 %s:%d\n", ServerAddr, Port)
  23. // 启动消息处理和心跳协程
  24. wg.Add(2)
  25. go func() {
  26. defer wg.Done()
  27. broadcast.HandleStcCmd(conn) // 处理消息
  28. }()
  29. go func() {
  30. defer wg.Done()
  31. Sendheartbeat(conn) // 发送心跳
  32. }()
  33. // 等待连接断开
  34. wg.Wait()
  35. fmt.Println("检测到连接断开,准备重新连接...")
  36. conn.Close() // 显式关闭旧连接
  37. time.Sleep(time.Second * 1) // 可选:断开后等待1秒再重试
  38. }
  39. }
  40. // 返回错误而不是终止程序
  41. func CreateConnection(ServerAddr string, Port int) (net.Conn, error) {
  42. fmt.Println("========== conn server ==========")
  43. conn, err := net.DialTCP("tcp", &net.TCPAddr{
  44. IP: net.ParseIP("0.0.0.0"),
  45. Port: 10201,
  46. }, &net.TCPAddr{
  47. IP: net.ParseIP(ServerAddr),
  48. Port: Port,
  49. })
  50. if err != nil {
  51. return nil, err
  52. }
  53. fileDesc, _ := conn.File()
  54. fd := fileDesc.Fd()
  55. syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1)
  56. return conn, nil
  57. }
  58. func Sendheartbeat(conn net.Conn) {
  59. var count uint8
  60. protocol := msgdata.NewProtocol()
  61. // 初始化协议...
  62. ticker := time.NewTicker(2 * time.Second)
  63. defer ticker.Stop()
  64. for {
  65. select {
  66. case <-ticker.C:
  67. count++
  68. // 编码并发送数据...
  69. encoded, err := protocol.Encode()
  70. if err != nil {
  71. fmt.Printf("编码失败: %v\n", err)
  72. return
  73. }
  74. _, err = conn.Write(encoded)
  75. if err != nil {
  76. fmt.Printf("发送心跳失败: %v\n", err)
  77. return // 触发重连
  78. }
  79. }
  80. }
  81. }
  82. // 检查PA server是主状态还是从状态
  83. func CheckMaster(conn net.Conn) bool {
  84. // var count uint8
  85. //init heartbeat data
  86. protocol := msgdata.NewProtocol()
  87. protocol.SourceID = 0x02
  88. protocol.DestinationID = 0x01
  89. protocol.MessageID = 0x21
  90. protocol.DataLength = 0x04
  91. return false
  92. }