gf/g/net/gudp/gudp_server.go

96 lines
2.3 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 {
conn *Conn // UDP server connection object.
address string // Listening address.
handler func (*Conn)
2017-11-23 10:21:28 +08:00
}
2017-12-30 17:09:00 +08:00
// Server表用以存储和检索名称与Server对象之间的关联关系
var serverMapping = gmap.NewStrAnyMap()
2017-12-30 17:09:00 +08:00
// 获取/创建一个空配置的UDP Server
// 单例模式请保证name的唯一性
2019-06-04 23:33:46 +08:00
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对象并且可以选择指定一个单例名字
2019-06-04 23:33:46 +08:00
func NewServer(address string, handler func (*Conn), names...string) *Server {
s := &Server{
address : address,
handler : handler,
}
2017-12-30 17:09:00 +08:00
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)) {
2018-07-18 11:43:30 +08:00
s.handler = handler
}
// Close closes the connection.
// It will make server shutdowns immediately.
func (s *Server) Close() error {
return s.conn.Close()
}
2018-07-18 11:43:30 +08:00
// 执行监听
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
}
s.conn = NewConnByNetConn(conn)
s.handler(s.conn)
return nil
2018-07-18 11:43:30 +08:00
}