package net import ( "fmt" "github.com/golang/protobuf/proto" "net" "pro2d/components/db" "pro2d/components/etcd" "pro2d/conf" "pro2d/models" "pro2d/protos/pb" "pro2d/utils" "sync" ) type ActionHandler func (msg *MsgPkg) (int32, proto.Message) var ActionMap map[pb.ProtoCode]ActionHandler type Server struct { SConf *conf.SConf Clients *sync.Map EtcdClient *etcd.EtcdClient } func NewServer(sConf *conf.SConf) *Server { return &Server{ SConf: sConf, Clients: new(sync.Map), } } func (s *Server) OnRecv(msg *MsgPkg) { utils.Sugar.Debugf("cmd: %d, data: %s", msg.Head.Cmd, msg.Body) if md, ok := ActionMap[pb.ProtoCode(msg.Head.Cmd)]; ok { errCode, protomsg := md(msg) rsp, err := proto.Marshal(protomsg) if err != nil { msg.Conn.SendMsgByCode(-100, msg.Head.Cmd, nil) return } msg.Conn.SendMsgByCode(errCode, msg.Head.Cmd, rsp) return } utils.Sugar.Errorf("protocode not handler: %d", msg.Head.Cmd) } func (s *Server) OnClose(conn *Connection) { s.Clients.Delete(conn.Id) } func (s *Server)Start() error { //mongo 初始化 db.MongoDatabase = db.MongoClient.Database(conf.GlobalConf.AccountConf.DBName) models.InitGameServerModels() //Etcd 初始化 s.EtcdClient = etcd.NewEtcdClient(conf.GlobalConf.Etcd) s.EtcdClient.PutWithLeasePrefix(conf.GlobalConf.GameConf.Name, conf.GlobalConf.GameConf.ID, fmt.Sprintf("%s:%d", conf.GlobalConf.GameConf.IP, conf.GlobalConf.GameConf.Port), 5) port := fmt.Sprintf(":%d", s.SConf.Port) l, err := net.Listen("tcp", port) if err != nil { return err } utils.Sugar.Debugf("listen on %s\n", port) id := 0 for { conn, err := l.Accept() if err != nil { return err } id++ client := NewConn(id, conn, s) s.Clients.Store(id, client) go client.Start() } } func (s *Server)Stop() { }