github.com/zhongdalu/gf@v1.0.0/g/net/gudp/gudp_server.go (about) 1 // Copyright 2017 gf Author(https://github.com/zhongdalu/gf). 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/zhongdalu/gf. 6 7 package gudp 8 9 import ( 10 "errors" 11 "github.com/zhongdalu/gf/g/container/gmap" 12 "github.com/zhongdalu/gf/g/os/glog" 13 "github.com/zhongdalu/gf/g/util/gconv" 14 "net" 15 ) 16 17 const ( 18 gDEFAULT_SERVER = "default" 19 ) 20 21 // tcp server结构体 22 type Server struct { 23 conn *Conn // UDP server connection object. 24 address string // Listening address. 25 handler func(*Conn) 26 } 27 28 // Server表,用以存储和检索名称与Server对象之间的关联关系 29 var serverMapping = gmap.NewStrAnyMap() 30 31 // 获取/创建一个空配置的UDP Server 32 // 单例模式,请保证name的唯一性 33 func GetServer(name ...interface{}) *Server { 34 serverName := gDEFAULT_SERVER 35 if len(name) > 0 { 36 serverName = gconv.String(name[0]) 37 } 38 if s := serverMapping.Get(serverName); s != nil { 39 return s.(*Server) 40 } 41 s := NewServer("", nil) 42 serverMapping.Set(serverName, s) 43 return s 44 } 45 46 // 创建一个tcp server对象,并且可以选择指定一个单例名字 47 func NewServer(address string, handler func(*Conn), names ...string) *Server { 48 s := &Server{ 49 address: address, 50 handler: handler, 51 } 52 if len(names) > 0 { 53 serverMapping.Set(names[0], s) 54 } 55 return s 56 } 57 58 // 设置参数 - address 59 func (s *Server) SetAddress(address string) { 60 s.address = address 61 } 62 63 // 设置参数 - handler 64 func (s *Server) SetHandler(handler func(*Conn)) { 65 s.handler = handler 66 } 67 68 // Close closes the connection. 69 // It will make server shutdowns immediately. 70 func (s *Server) Close() error { 71 return s.conn.Close() 72 } 73 74 // 执行监听 75 func (s *Server) Run() error { 76 if s.handler == nil { 77 err := errors.New("start running failed: socket handler not defined") 78 glog.Error(err) 79 return err 80 } 81 addr, err := net.ResolveUDPAddr("udp", s.address) 82 if err != nil { 83 glog.Error(err) 84 return err 85 } 86 conn, err := net.ListenUDP("udp", addr) 87 if err != nil { 88 glog.Error(err) 89 return err 90 } 91 s.conn = NewConnByNetConn(conn) 92 s.handler(s.conn) 93 return nil 94 }