game.go
2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package service
import (
"fmt"
"math/rand"
_ "net/http/pprof"
"pro2d/cmd/gameserver/action"
"pro2d/common"
"pro2d/common/components"
"pro2d/common/db/mongoproxy"
"pro2d/common/db/redisproxy"
"pro2d/common/logger"
"pro2d/models"
"time"
"pro2d/common/etcd"
)
type GameServer struct {
components.IServer
EtcdClient *etcd.EtcdClient
}
func NewGameServer(sconf *common.SConf) (*GameServer, error) {
s := &GameServer{}
options := []components.ServerOption{
components.WithPlugin(components.NewPlugin(sconf.PluginPath)),
components.WithConnCbk(s.OnConnection),
components.WithMsgCbk(s.OnMessage),
components.WithCloseCbk(s.OnClose),
components.WithTimerCbk(s.OnTimer),
}
//加密
if sconf.Encipher {
options = append(options, components.WithSplitter(components.NewPBSplitter(components.NewAesEncipher())))
logger.Debug("open encipher aes...")
} else {
options = append(options, components.WithSplitter(components.NewPBSplitter(nil)))
}
iserver := components.NewServer(sconf.Port, options...)
iserver.SetActions(action.GetActionMap())
s.IServer = iserver
//mgo init
err := mongoproxy.ConnectMongo(sconf.MongoConf)
if err != nil {
return nil, err
}
models.InitGameModels()
//redis init
if err = redisproxy.ConnectRedis(sconf.RedisConf.DB, sconf.RedisConf.Auth, sconf.RedisConf.Address); err != nil {
return nil, err
}
//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 {
//设置随机种子
rand.Seed(time.Now().Unix())
return s.IServer.Start()
}
func (s *GameServer) Stop() {
s.IServer.Stop()
mongoproxy.CloseMongo()
redisproxy.CloseRedis()
s.EtcdClient.Close()
}
func (s *GameServer) OnConnection(conn components.IConnection) {
agent := NewAgent(s)
agent.OnConnection(conn)
s.GetConnManage().AddConn(conn.GetID(), agent)
}
func (s *GameServer) OnMessage(msg components.IMessage) {
agent := s.GetConnManage().GetConn(msg.GetSID())
if agent == nil {
return
}
agent.(*Agent).OnMessage(msg)
}
func (s *GameServer) OnTimer(conn components.IConnection) {
agent := s.GetConnManage().GetConn(conn.GetID())
if agent == nil {
return
}
agent.(*Agent).OnTimer()
}
func (s *GameServer) OnClose(conn components.IConnection) {
agent := s.GetConnManage().GetConn(conn.GetID())
if agent == nil {
return
}
agent.(*Agent).OnClose()
s.GetConnManage().DelConn(conn.GetID())
}