index.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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: 0,
  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. protocol := msgdata.NewProtocol()
  43. protocol.SourceID = 0x02
  44. protocol.DestinationID = 0x01
  45. protocol.MessageID = 0x21
  46. protocol.DataLength = 0x04
  47. ticker := time.NewTicker(2 * time.Second)
  48. defer ticker.Stop()
  49. for range ticker.C {
  50. count = count + 1
  51. protocol.Data = []byte{count, 0x00, 0x00, 0x00}
  52. encoded, errEn := protocol.Encode()
  53. if errEn != nil {
  54. fmt.Println("Encode error:", errEn)
  55. return
  56. }
  57. _, err := conn.Write(encoded)
  58. if err != nil {
  59. fmt.Println("send heartbeat err:", err)
  60. return
  61. }
  62. }
  63. }
  64. // 检查PA server是主状态还是从状态
  65. func CheckMaster(conn net.Conn) bool {
  66. // var count uint8
  67. //init heartbeat data
  68. protocol := msgdata.NewProtocol()
  69. protocol.SourceID = 0x02
  70. protocol.DestinationID = 0x01
  71. protocol.MessageID = 0x21
  72. protocol.DataLength = 0x04
  73. return false
  74. }