index.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. package stc
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "pbx-api-gin/internal/app/stc/broadcast"
  7. msgdata "pbx-api-gin/internal/app/stc/data"
  8. "pbx-api-gin/internal/app/stc/socket"
  9. "pbx-api-gin/pkg/lfshook"
  10. "sync"
  11. "syscall"
  12. "time"
  13. )
  14. const RemotePort = 10100
  15. const LocalPort = 10201
  16. //const RemoteAddr = "192.168.17.14"
  17. const RemoteAddr = "10.0.11.11"
  18. func StartStcConnection(conn net.Conn) {
  19. //var conn net.Conn
  20. //var wg sync.WaitGroup
  21. var connMux sync.Mutex // 保护 conn 的读写
  22. //var err error
  23. for {
  24. // 尝试建立连接
  25. conn1, err := CreateConnection()
  26. if err != nil {
  27. time.Sleep(2 * time.Second)
  28. continue
  29. }
  30. connMux.Lock()
  31. oldConn := conn
  32. socket.Conn = conn1
  33. connMux.Unlock()
  34. // 关闭旧连接(如果存在)
  35. if oldConn != nil {
  36. oldConn.Close()
  37. lfshook.NewLogger().Logger.Infof("Closed previous connection")
  38. }
  39. // 使用 context 控制所有协程的生命周期
  40. ctx, cancel := context.WithCancel(context.Background())
  41. lfshook.NewLogger().Logger.Infof("Connect success :%s:%d", RemoteAddr, RemotePort)
  42. // 启动消息处理和心跳协程
  43. // 启动消息处理
  44. go func() {
  45. defer func() {
  46. cancel() // 一旦任一协程退出,取消所有
  47. }()
  48. broadcast.HandleStcCmd(ctx, conn1) // 改造 HandleStcCmd 接收 ctx
  49. }()
  50. // 启动心跳
  51. go func() {
  52. defer func() {
  53. cancel()
  54. }()
  55. Sendheartbeat(ctx, conn1) // 改造 Sendheartbeat 接收 ctx
  56. }()
  57. // 等待连接断开(监听连接状态)
  58. <-ctx.Done()
  59. // 连接已断开,清理
  60. cancel() // 确保所有 cancel 被调用
  61. conn1.Close()
  62. lfshook.NewLogger().Logger.Info("Reconnecting in 1 second...")
  63. time.Sleep(time.Second) // 重连前等待
  64. }
  65. }
  66. // 返回错误而不是终止程序
  67. func CreateConnection() (net.Conn, error) {
  68. lfshook.NewLogger().Logger.Infof("========Connect server IP:%s :Port:%d", RemoteAddr, RemotePort)
  69. // 创建 Dialer
  70. dialer := &net.Dialer{
  71. LocalAddr: &net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: LocalPort}, // 固定本地端口
  72. Control: controlTCPConn,
  73. }
  74. DialAddr := fmt.Sprintf("%s:%d", RemoteAddr, RemotePort)
  75. conn, err := dialer.Dial("tcp", DialAddr)
  76. if err != nil {
  77. lfshook.NewLogger().Logger.Infof("========Connect server err :%+v", err)
  78. return nil, err
  79. }
  80. return conn, nil
  81. }
  82. func controlTCPConn(network, address string, c syscall.RawConn) error {
  83. return c.Control(func(fd uintptr) {
  84. syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1)
  85. // 注意:SO_REUSEPORT 在某些系统可用(如 Linux),但非标准
  86. })
  87. }
  88. func Sendheartbeat(ctx context.Context, conn net.Conn) {
  89. var count uint8
  90. protocol := msgdata.NewProtocol()
  91. // 初始化协议...
  92. ticker := time.NewTicker(2 * time.Second)
  93. defer ticker.Stop()
  94. for {
  95. select {
  96. case <-ctx.Done():
  97. return
  98. case <-ticker.C:
  99. count++
  100. // 编码并发送数据...
  101. encoded, err := protocol.Encode()
  102. if err != nil {
  103. fmt.Printf("encode err : %v\n", err)
  104. return
  105. }
  106. if conn != nil {
  107. _, err = conn.Write(encoded)
  108. if err != nil {
  109. fmt.Printf("Send hearbeat err: %v\n", err)
  110. conn.Close()
  111. return // 触发重连
  112. }
  113. }
  114. }
  115. }
  116. }
  117. // 检查PA server是主状态还是从状态
  118. func CheckMaster(conn net.Conn) bool {
  119. // var count uint8
  120. //init heartbeat data
  121. protocol := msgdata.NewProtocol()
  122. protocol.SourceID = 0x02
  123. protocol.DestinationID = 0x01
  124. protocol.MessageID = 0x21
  125. protocol.DataLength = 0x04
  126. return false
  127. }