index.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. fmt.Println("==========conn server============")
  24. conn, err := net.DialTCP("tcp", &net.TCPAddr{
  25. IP: net.ParseIP("0.0.0.0"),
  26. Port: 10201,
  27. }, &net.TCPAddr{
  28. IP: net.ParseIP(ServerAddr),
  29. Port: Port,
  30. })
  31. if err != nil {
  32. fmt.Println("Error conn server:", err)
  33. log.Fatal(err)
  34. return nil
  35. }
  36. fileDesc, _ := conn.File()
  37. fd := fileDesc.Fd()
  38. syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1)
  39. return conn
  40. }
  41. func Sendheartbeat(conn net.Conn) {
  42. var count uint8
  43. //init heartbeat data ============================
  44. //return
  45. protocol := msgdata.NewProtocol()
  46. protocol.SourceID = 0x02
  47. protocol.DestinationID = 0x01
  48. protocol.MessageID = 0x21
  49. protocol.DataLength = 0x04
  50. ticker := time.NewTicker(2 * time.Second)
  51. defer ticker.Stop()
  52. for range ticker.C {
  53. count = count + 1
  54. protocol.Data = []byte{count, 0x00, 0x00, 0x00}
  55. encoded, errEn := protocol.Encode()
  56. if errEn != nil {
  57. fmt.Println("Encode error:", errEn)
  58. return
  59. }
  60. _, err := conn.Write(encoded)
  61. if err != nil {
  62. fmt.Println("send heartbeat err:", err)
  63. return
  64. }
  65. }
  66. }
  67. // 检查PA server是主状态还是从状态
  68. func CheckMaster(conn net.Conn) bool {
  69. // var count uint8
  70. //init heartbeat data
  71. protocol := msgdata.NewProtocol()
  72. protocol.SourceID = 0x02
  73. protocol.DestinationID = 0x01
  74. protocol.MessageID = 0x21
  75. protocol.DataLength = 0x04
  76. return false
  77. }