2017-12-29 16:03:30 +08:00
|
|
|
|
// Copyright 2017 gf Author(https://gitee.com/johng/gf). All Rights Reserved.
|
|
|
|
|
//
|
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
|
|
|
|
// You can obtain one at https://gitee.com/johng/gf.
|
|
|
|
|
|
2018-01-03 10:38:53 +08:00
|
|
|
|
// UDP服务端
|
2017-11-23 10:21:28 +08:00
|
|
|
|
package gudp
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"net"
|
2017-12-30 17:09:00 +08:00
|
|
|
|
"gitee.com/johng/gf/g/container/gmap"
|
2017-11-23 10:21:28 +08:00
|
|
|
|
)
|
|
|
|
|
|
2017-12-30 18:35:24 +08:00
|
|
|
|
const (
|
|
|
|
|
gDEFAULT_SERVER = "default"
|
|
|
|
|
)
|
|
|
|
|
|
2017-11-23 10:21:28 +08:00
|
|
|
|
// tcp server结构体
|
2017-12-29 22:11:03 +08:00
|
|
|
|
type Server struct {
|
2017-11-23 10:21:28 +08:00
|
|
|
|
address string
|
|
|
|
|
handler func (*net.UDPConn)
|
|
|
|
|
}
|
|
|
|
|
|
2017-12-30 17:09:00 +08:00
|
|
|
|
// Server表,用以存储和检索名称与Server对象之间的关联关系
|
|
|
|
|
var serverMapping = gmap.NewStringInterfaceMap()
|
|
|
|
|
|
|
|
|
|
// 获取/创建一个空配置的UDP Server
|
|
|
|
|
// 单例模式,请保证name的唯一性
|
2017-12-30 18:35:24 +08:00
|
|
|
|
func GetServer(names...string) (*Server) {
|
|
|
|
|
name := gDEFAULT_SERVER
|
|
|
|
|
if len(names) > 0 {
|
|
|
|
|
name = names[0]
|
|
|
|
|
}
|
2017-12-30 17:09:00 +08:00
|
|
|
|
if s := serverMapping.Get(name); s != nil {
|
|
|
|
|
return s.(*Server)
|
2017-11-23 10:21:28 +08:00
|
|
|
|
}
|
2017-12-30 17:09:00 +08:00
|
|
|
|
s := NewServer("", nil)
|
|
|
|
|
serverMapping.Set(name, s)
|
|
|
|
|
return s
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 创建一个tcp server对象,并且可以选择指定一个单例名字
|
|
|
|
|
func NewServer (address string, handler func (*net.UDPConn), names...string) *Server {
|
|
|
|
|
s := &Server{address, handler}
|
|
|
|
|
if len(names) > 0 {
|
|
|
|
|
serverMapping.Set(names[0], s)
|
2017-11-23 10:21:28 +08:00
|
|
|
|
}
|
2017-12-30 17:09:00 +08:00
|
|
|
|
return s
|
2017-11-23 10:21:28 +08:00
|
|
|
|
}
|
|
|
|
|
|