gf/g/net/gudp/gudp_server.go

86 lines
2.0 KiB
Go
Raw Normal View History

// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
2017-12-29 16:03:30 +08:00
//
// 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://github.com/gogf/gf.
2017-12-29 16:03:30 +08:00
2018-07-18 11:43:30 +08:00
2017-11-23 10:21:28 +08:00
package gudp
import (
"github.com/gogf/gf/g/os/glog"
2017-11-23 10:21:28 +08:00
"net"
2018-07-18 11:43:30 +08:00
"errors"
"github.com/gogf/gf/g/container/gmap"
"github.com/gogf/gf/g/util/gconv"
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
2018-07-18 11:43:30 +08:00
handler func (*Conn)
2017-11-23 10:21:28 +08:00
}
2017-12-30 17:09:00 +08:00
// Server表用以存储和检索名称与Server对象之间的关联关系
var serverMapping = gmap.NewStringInterfaceMap()
// 获取/创建一个空配置的UDP Server
// 单例模式请保证name的唯一性
func GetServer(name...interface{}) (*Server) {
serverName := gDEFAULT_SERVER
if len(name) > 0 {
serverName = gconv.String(name[0])
2017-12-30 18:35:24 +08:00
}
if s := serverMapping.Get(serverName); s != nil {
2017-12-30 17:09:00 +08:00
return s.(*Server)
2017-11-23 10:21:28 +08:00
}
2017-12-30 17:09:00 +08:00
s := NewServer("", nil)
serverMapping.Set(serverName, s)
2017-12-30 17:09:00 +08:00
return s
}
// 创建一个tcp server对象并且可以选择指定一个单例名字
2018-07-18 11:43:30 +08:00
func NewServer (address string, handler func (*Conn), names...string) *Server {
2017-12-30 17:09:00 +08:00
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
}
2018-07-18 11:43:30 +08:00
// 设置参数 - address
func (s *Server) SetAddress (address string) {
s.address = address
}
// 设置参数 - handler
func (s *Server) SetHandler (handler func (*Conn)) {
s.handler = handler
}
// 执行监听
func (s *Server) Run() error {
if s.handler == nil {
err := errors.New("start running failed: socket handler not defined")
glog.Error(err)
return err
2018-07-18 11:43:30 +08:00
}
addr, err := net.ResolveUDPAddr("udp", s.address)
if err != nil {
glog.Error(err)
2018-07-18 11:43:30 +08:00
return err
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
glog.Error(err)
2018-07-18 11:43:30 +08:00
return err
}
for {
s.handler(NewConnByNetConn(conn))
}
}