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