gudp_server.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gudp
  7. import (
  8. "fmt"
  9. "net"
  10. "sync"
  11. "github.com/gogf/gf/v2/container/gmap"
  12. "github.com/gogf/gf/v2/errors/gcode"
  13. "github.com/gogf/gf/v2/errors/gerror"
  14. "github.com/gogf/gf/v2/text/gstr"
  15. "github.com/gogf/gf/v2/util/gconv"
  16. )
  17. const (
  18. // FreePortAddress marks the server listens using random free port.
  19. FreePortAddress = ":0"
  20. )
  21. const (
  22. defaultServer = "default"
  23. )
  24. // Server is the UDP server.
  25. type Server struct {
  26. mu sync.Mutex // Used for Server.listen concurrent safety. -- The golang test with data race checks this.
  27. conn *Conn // UDP server connection object.
  28. address string // UDP server listening address.
  29. handler func(*Conn) // Handler for UDP connection.
  30. }
  31. var (
  32. // serverMapping is used for instance name to its UDP server mappings.
  33. serverMapping = gmap.NewStrAnyMap(true)
  34. )
  35. // GetServer creates and returns a UDP server instance with given name.
  36. func GetServer(name ...interface{}) *Server {
  37. serverName := defaultServer
  38. if len(name) > 0 && name[0] != "" {
  39. serverName = gconv.String(name[0])
  40. }
  41. if s := serverMapping.Get(serverName); s != nil {
  42. return s.(*Server)
  43. }
  44. s := NewServer("", nil)
  45. serverMapping.Set(serverName, s)
  46. return s
  47. }
  48. // NewServer creates and returns a UDP server.
  49. // The optional parameter `name` is used to specify its name, which can be used for
  50. // GetServer function to retrieve its instance.
  51. func NewServer(address string, handler func(*Conn), name ...string) *Server {
  52. s := &Server{
  53. address: address,
  54. handler: handler,
  55. }
  56. if len(name) > 0 && name[0] != "" {
  57. serverMapping.Set(name[0], s)
  58. }
  59. return s
  60. }
  61. // SetAddress sets the server address for UDP server.
  62. func (s *Server) SetAddress(address string) {
  63. s.address = address
  64. }
  65. // SetHandler sets the connection handler for UDP server.
  66. func (s *Server) SetHandler(handler func(*Conn)) {
  67. s.handler = handler
  68. }
  69. // Close closes the connection.
  70. // It will make server shutdowns immediately.
  71. func (s *Server) Close() (err error) {
  72. s.mu.Lock()
  73. defer s.mu.Unlock()
  74. err = s.conn.Close()
  75. if err != nil {
  76. err = gerror.Wrap(err, "connection failed")
  77. }
  78. return
  79. }
  80. // Run starts listening UDP connection.
  81. func (s *Server) Run() error {
  82. if s.handler == nil {
  83. err := gerror.NewCode(gcode.CodeMissingConfiguration, "start running failed: socket handler not defined")
  84. return err
  85. }
  86. addr, err := net.ResolveUDPAddr("udp", s.address)
  87. if err != nil {
  88. err = gerror.Wrapf(err, `net.ResolveUDPAddr failed for address "%s"`, s.address)
  89. return err
  90. }
  91. conn, err := net.ListenUDP("udp", addr)
  92. if err != nil {
  93. err = gerror.Wrapf(err, `net.ListenUDP failed for address "%s"`, s.address)
  94. return err
  95. }
  96. s.mu.Lock()
  97. s.conn = NewConnByNetConn(conn)
  98. s.mu.Unlock()
  99. s.handler(s.conn)
  100. return nil
  101. }
  102. // GetListenedAddress retrieves and returns the address string which are listened by current server.
  103. func (s *Server) GetListenedAddress() string {
  104. if !gstr.Contains(s.address, FreePortAddress) {
  105. return s.address
  106. }
  107. var (
  108. address = s.address
  109. listenedPort = s.GetListenedPort()
  110. )
  111. address = gstr.Replace(address, FreePortAddress, fmt.Sprintf(`:%d`, listenedPort))
  112. return address
  113. }
  114. // GetListenedPort retrieves and returns one port which is listened to by current server.
  115. func (s *Server) GetListenedPort() int {
  116. s.mu.Lock()
  117. defer s.mu.Unlock()
  118. if ln := s.conn; ln != nil {
  119. return ln.LocalAddr().(*net.UDPAddr).Port
  120. }
  121. return -1
  122. }