game.go 1.98 KB
package main

import (
	"fmt"
	_ "net/http/pprof"
	"pro2d/common"
	"pro2d/common/components"
	"pro2d/common/db"
	"pro2d/models"

	"pro2d/common/etcd"
	"sync"
)

type GameServer struct {
	components.IServer
	EtcdClient *etcd.EtcdClient

	Agents 		*sync.Map
}

func NewGameServer(sconf *common.SConf) (*GameServer, error)  {
	s := &GameServer{
		Agents:  new(sync.Map),
	}

	options := []components.ServerOption{
		components.WithPlugin(components.NewPlugin(sconf.PluginPath)),
		components.WithSplitter(components.NewPBSplitter()),
		components.WithConnCbk(s.OnConnection),
		components.WithMsgCbk(s.OnMessage),
		components.WithCloseCbk(s.OnClose),
		components.WithTimerCbk(s.OnTimer),
	}

	iserver := components.NewServer(sconf.Port, options...)
	s.IServer = iserver

	//mgo init
	err := db.ConnectMongo(sconf.MongoConf)
	if err != nil {
		return nil, err
	}
	models.InitModels()

	//Etcd 初始化
	s.EtcdClient, err = etcd.NewEtcdClient(common.GlobalConf.Etcd)
	if err != nil {
		return nil, err
	}
	s.EtcdClient.PutWithLeasePrefix(common.GlobalConf.GameConf.Name, common.GlobalConf.GameConf.ID, fmt.Sprintf("%s:%d", common.GlobalConf.GameConf.IP, common.GlobalConf.GameConf.Port), 5)

	return s, nil
}

func (s *GameServer) Start() error {
	return s.IServer.Start()
}

func (s *GameServer) Stop()  {
	s.IServer.Stop()

	db.CloseMongo()
	s.EtcdClient.Close()
}

func (s *GameServer) OnConnection(conn components.IConnection)  {
	agent := NewAgent(s)
	agent.OnConnection(conn)
	s.Agents.Store(conn.GetID(),agent)
}

func (s *GameServer) OnMessage(msg components.IMessage)  {
	agent, ok := s.Agents.Load(msg.GetSession().GetID())
	if !ok {
		return
	}
	agent.(*Agent).OnMessage(msg)
}

func (s *GameServer) OnTimer(conn components.IConnection)  {
	agent, ok := s.Agents.Load(conn.GetID())
	if !ok {
		return
	}
	agent.(*Agent).OnTimer()
}

func (s *GameServer) OnClose(conn components.IConnection)  {
	agent, ok := s.Agents.Load(conn.GetID())
	if !ok {
		return
	}
	agent.(*Agent).OnClose()
	s.Agents.Delete(conn.GetID())
}