index.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package stc
  2. import (
  3. "fmt"
  4. "log"
  5. "net"
  6. "pbx-api-gin/internal/app/stc/broadcast"
  7. msgdata "pbx-api-gin/internal/app/stc/data"
  8. "syscall"
  9. "time"
  10. )
  11. func StartStcConnection(conn net.Conn) {
  12. //read msg
  13. go func(conn net.Conn) {
  14. broadcast.HandleStcCmd(conn)
  15. }(conn)
  16. //heartbeat
  17. go func(conn net.Conn) {
  18. Sendheartbeat(conn)
  19. }(conn)
  20. }
  21. func CreateConnection(ServerAddr string, Port int) net.Conn {
  22. // connect server
  23. conn, err := net.DialTCP("tcp", &net.TCPAddr{
  24. IP: net.ParseIP("0.0.0.0"),
  25. Port: 10201,
  26. }, &net.TCPAddr{
  27. IP: net.ParseIP(ServerAddr),
  28. Port: Port,
  29. })
  30. if err != nil {
  31. fmt.Println("Error conn server:", err)
  32. log.Fatal(err)
  33. }
  34. fileDesc, _ := conn.File()
  35. fd := fileDesc.Fd()
  36. syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1)
  37. return conn
  38. }
  39. func Sendheartbeat(conn net.Conn) {
  40. var count uint8
  41. //init heartbeat data ============================
  42. //return
  43. protocol := msgdata.NewProtocol()
  44. protocol.SourceID = 0x02
  45. protocol.DestinationID = 0x01
  46. protocol.MessageID = 0x21
  47. protocol.DataLength = 0x04
  48. ticker := time.NewTicker(2 * time.Second)
  49. defer ticker.Stop()
  50. for range ticker.C {
  51. count = count + 1
  52. protocol.Data = []byte{count, 0x00, 0x00, 0x00}
  53. encoded, errEn := protocol.Encode()
  54. if errEn != nil {
  55. fmt.Println("Encode error:", errEn)
  56. return
  57. }
  58. _, err := conn.Write(encoded)
  59. if err != nil {
  60. fmt.Println("send heartbeat err:", err)
  61. return
  62. }
  63. }
  64. }
  65. // 检查PA server是主状态还是从状态
  66. func CheckMaster(conn net.Conn) bool {
  67. // var count uint8
  68. //init heartbeat data
  69. protocol := msgdata.NewProtocol()
  70. protocol.SourceID = 0x02
  71. protocol.DestinationID = 0x01
  72. protocol.MessageID = 0x21
  73. protocol.DataLength = 0x04
  74. return false
  75. }