func (client *TCPClient) init() { client.Lock() defer client.Unlock() if client.ConnNum <= 0 { client.ConnNum = 1 log.Release("invalid ConnNum, reset to %v", client.ConnNum) } if client.ConnectInterval <= 0 { client.ConnectInterval = 3 * time.Second log.Release("invalid ConnectInterval, reset to %v", client.ConnectInterval) } if client.PendingWriteNum <= 0 { client.PendingWriteNum = 100 log.Release("invalid PendingWriteNum, reset to %v", client.PendingWriteNum) } if client.NewAgent == nil { log.Fatal("NewAgent must not be nil") } if client.conns != nil { log.Fatal("client is running") } client.conns = make(ConnSet) client.closeFlag = false // msg parser msgParser := NewMsgParser() msgParser.SetMsgLen(client.LenMsgLen, client.MinMsgLen, client.MaxMsgLen) msgParser.SetByteOrder(client.LittleEndian) client.msgParser = msgParser }
//初始化TCP服务器 func (server *TCPServer) init() { ln, err := net.Listen("tcp", server.Addr) //监听 if err != nil { log.Fatal("%v", err) } if server.MaxConnNum <= 0 { //最大连接数小于0,重置到100 server.MaxConnNum = 100 log.Release("invalid MaxConnNum, reset to %v", server.MaxConnNum) } if server.PendingWriteNum <= 0 { //发送缓冲区长度小于0,重置到100 server.PendingWriteNum = 100 log.Release("invalid PendingWriteNum, reset to %v", server.PendingWriteNum) } if server.NewAgent == nil { //创建代理函数不能为空 log.Fatal("NewAgent must not be nil") } server.ln = ln //保存监听连接器 server.conns = make(ConnSet) //创建连接集合 server.closeFlag = false //关闭标志 // msg parser msgParser := NewMsgParser() //创建消息解析器 msgParser.SetMsgLen(server.LenMsgLen, server.MinMsgLen, server.MaxMsgLen) //设置消息长度 msgParser.SetByteOrder(server.LittleEndian) //设置字节序 server.msgParser = msgParser //保存消息解析器 }
func (server *TCPServer) init() { ln, err := net.Listen("tcp", server.Addr) if err != nil { log.Fatal("%v", err) } if server.MaxConnNum <= 0 { server.MaxConnNum = 100 log.Release("invalid MaxConnNum, reset to %v", server.MaxConnNum) } if server.PendingWriteNum <= 0 { server.PendingWriteNum = 100 log.Release("invalid PendingWriteNum, reset to %v", server.PendingWriteNum) } if server.NewAgent == nil { log.Fatal("NewAgent must not be nil") } server.ln = ln server.conns = make(ConnSet) // msg parser msgParser := NewMsgParser() msgParser.SetMsgLen(server.LenMsgLen, server.MinMsgLen, server.MaxMsgLen) msgParser.SetByteOrder(server.LittleEndian) server.msgParser = msgParser }
func init() { data, err := ioutil.ReadFile("conf/server.json") if err != nil { log.Fatal("%v", err) } err = json.Unmarshal(data, &Server) if err != nil { log.Fatal("%v", err) } }
func init() { data, err := ioutil.ReadFile("conf/server.json") //读取服务器配置 位于leafserver/bin/conf/server.json if err != nil { log.Fatal("%v", err) } err = json.Unmarshal(data, &Server) //解析数据到Server中 if err != nil { log.Fatal("%v", err) } }
func loadDBConfig() { data, err := ioutil.ReadFile("conf/db.json") if err != nil { log.Fatal("%v", err) } err = json.Unmarshal(data, &DB) if err != nil { log.Fatal("%v", err) } }
// It's dangerous to call the method on routing or marshaling (unmarshaling) //设置消息处理函数 func (p *Processor) SetHandler(msg interface{}, msgHandler MsgHandler) { msgType := reflect.TypeOf(msg) //消息类型 if msgType == nil || msgType.Kind() != reflect.Ptr { //判断合法性 log.Fatal("json message pointer required") } msgID := msgType.Elem().Name() //获取消息ID i, ok := p.msgInfo[msgID] //获取消息信息 if !ok { log.Fatal("message %v not registered", msgID) } i.msgHandler = msgHandler //保存消息处理函数 }
// It's dangerous to call the method on routing or marshaling (unmarshaling) //设置路由 func (p *Processor) SetRouter(msg interface{}, msgRouter *chanrpc.Server) { msgType := reflect.TypeOf(msg) //获取消息类型 if msgType == nil || msgType.Kind() != reflect.Ptr { //判断消息合法性 log.Fatal("json message pointer required") } msgID := msgType.Elem().Name() //获取消息类型本身的名字,也就是消息ID i, ok := p.msgInfo[msgID] //根据消息ID获得消息信息 if !ok { //获取消息信息失败 log.Fatal("message %v not registered", msgID) } i.msgRouter = msgRouter //保存RPC服务器引用 }
func readRf(st interface{}) *recordfile.RecordFile { rf, err := recordfile.New(st) if err != nil { log.Fatal("%v", err) } fn := reflect.TypeOf(st).Name() + ".txt" err = rf.Read("gamedata/" + fn) if err != nil { log.Fatal("%v: %v", fn, err) } return rf }
// It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) SetHandler(msg interface{}, msgHandler MsgHandler) { msgType := reflect.TypeOf(msg) if msgType == nil || msgType.Kind() != reflect.Ptr { log.Fatal("json message pointer required") } msgID := msgType.Elem().Name() i, ok := p.msgInfo[msgID] if !ok { log.Fatal("message %v not registered", msgID) } i.msgHandler = msgHandler }
func (server *WSServer) Start() { ln, err := net.Listen("tcp", server.Addr) if err != nil { log.Fatal("%v", err) } if server.MaxConnNum <= 0 { server.MaxConnNum = 100 log.Release("invalid MaxConnNum, reset to %v", server.MaxConnNum) } if server.PendingWriteNum <= 0 { server.PendingWriteNum = 100 log.Release("invalid PendingWriteNum, reset to %v", server.PendingWriteNum) } if server.MaxMsgLen <= 0 { server.MaxMsgLen = 4096 log.Release("invalid MaxMsgLen, reset to %v", server.MaxMsgLen) } if server.HTTPTimeout <= 0 { server.HTTPTimeout = 10 * time.Second log.Release("invalid HTTPTimeout, reset to %v", server.HTTPTimeout) } if server.NewAgent == nil { log.Fatal("NewAgent must not be nil") } server.ln = ln server.handler = &WSHandler{ maxConnNum: server.MaxConnNum, pendingWriteNum: server.PendingWriteNum, maxMsgLen: server.MaxMsgLen, newAgent: server.NewAgent, conns: make(WebsocketConnSet), upgrader: websocket.Upgrader{ HandshakeTimeout: server.HTTPTimeout, CheckOrigin: func(_ *http.Request) bool { return true }, }, } httpServer := &http.Server{ Addr: server.Addr, Handler: server.handler, ReadTimeout: server.HTTPTimeout, WriteTimeout: server.HTTPTimeout, MaxHeaderBytes: 1024, } go httpServer.Serve(ln) }
// It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) SetRawHandler(id uint16, msgRawHandler MsgHandler) { if id >= uint16(len(p.msgInfo)) { log.Fatal("message id %v not registered", id) } p.msgInfo[id].msgRawHandler = msgRawHandler }
// It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) Register(msg interface{}) { msgType := reflect.TypeOf(msg) if msgType == nil || msgType.Kind() != reflect.Ptr { log.Fatal("json message pointer required") } msgID := msgType.Elem().Name() if msgID == "" { log.Fatal("unnamed json message") } if _, ok := p.msgInfo[msgID]; ok { log.Fatal("message %v is already registered", msgID) } i := new(MsgInfo) i.msgType = msgType p.msgInfo[msgID] = i }
// It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) SetRawHandler(msgID string, msgRawHandler MsgHandler) { i, ok := p.msgInfo[msgID] if !ok { log.Fatal("message %v not registered", msgID) } i.msgRawHandler = msgRawHandler }
// It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) Register(msg proto.Message) { msgType := reflect.TypeOf(msg) if msgType == nil || msgType.Kind() != reflect.Ptr { log.Fatal("protobuf message pointer required") } if _, ok := p.msgID[msgType]; ok { log.Fatal("message %s is already registered", msgType) } if len(p.msgInfo) >= math.MaxUint16 { log.Fatal("too many protobuf messages (max = %v)", math.MaxUint16) } i := new(MsgInfo) i.msgType = msgType p.msgInfo = append(p.msgInfo, i) p.msgID[msgType] = uint16(len(p.msgInfo) - 1) }
// It's dangerous to call the method on routing or marshaling (unmarshaling) // 注册消息 func (p *Processor) Register(msg interface{}) { msgType := reflect.TypeOf(msg) //获取消息的类型 if msgType == nil || msgType.Kind() != reflect.Ptr { //判断消息的合法性,不能为空,需要是指针 log.Fatal("json message pointer required") } msgID := msgType.Elem().Name() //获取消息类型本身(不是指针)的名字,作为消息ID if msgID == "" { log.Fatal("unnamed json message") } if _, ok := p.msgInfo[msgID]; ok { //判断消息是否已经注册 log.Fatal("message %v is already registered", msgID) } i := new(MsgInfo) //新建一个消息信息 i.msgType = msgType //保存消息类型 p.msgInfo[msgID] = i //保存消息信息到映射中 }
// It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) SetHandler(msg proto.Message, msgHandler MsgHandler) { msgType := reflect.TypeOf(msg) id, ok := p.msgID[msgType] if !ok { log.Fatal("message %s not registered", msgType) } p.msgInfo[id].msgHandler = msgHandler }
// It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) SetRouter(msg proto.Message, msgRouter *chanrpc.Server) { msgType := reflect.TypeOf(msg) id, ok := p.msgID[msgType] if !ok { log.Fatal("message %s not registered", msgType) } p.msgInfo[id].msgRouter = msgRouter }
func init() { // mongodb if conf.Server.DBMaxConnNum <= 0 { conf.Server.DBMaxConnNum = 100 } db, err := mongodb.Dial(conf.Server.DBUrl, conf.Server.DBMaxConnNum) if err != nil { log.Fatal("dial mongodb error: %v", err) } mongoDB = db // users err = db.EnsureUniqueIndex("game", "users", []string{"accid"}) if err != nil { log.Fatal("ensure index error: %v", err) } err = db.EnsureCounter("game", "counters", "users") if err != nil { log.Fatal("ensure counter error: %v", err) } }
func (client *WSClient) init() { client.Lock() defer client.Unlock() if client.ConnNum <= 0 { client.ConnNum = 1 log.Release("invalid ConnNum, reset to %v", client.ConnNum) } if client.ConnectInterval <= 0 { client.ConnectInterval = 3 * time.Second log.Release("invalid ConnectInterval, reset to %v", client.ConnectInterval) } if client.PendingWriteNum <= 0 { client.PendingWriteNum = 100 log.Release("invalid PendingWriteNum, reset to %v", client.PendingWriteNum) } if client.MaxMsgLen <= 0 { client.MaxMsgLen = 4096 log.Release("invalid MaxMsgLen, reset to %v", client.MaxMsgLen) } if client.HandshakeTimeout <= 0 { client.HandshakeTimeout = 10 * time.Second log.Release("invalid HandshakeTimeout, reset to %v", client.HandshakeTimeout) } if client.NewAgent == nil { log.Fatal("NewAgent must not be nil") } if client.conns != nil { log.Fatal("client is running") } client.conns = make(WebsocketConnSet) client.closeFlag = false client.dialer = websocket.Dialer{ HandshakeTimeout: client.HandshakeTimeout, } }
// you must call the function before calling console.Init // goroutine not safe func Register(name string, help string, f interface{}, server *chanrpc.Server) { for _, c := range commands { if c.name() == name { log.Fatal("command %v is already registered", name) } } server.Register(name, f) c := new(ExternalCommand) c._name = name c._help = help c.server = server commands = append(commands, c) }
// you must call the function before calling console.Init,也就是在leaf.Run之前 // goroutine not safe // 注册命令 func Register(name string, help string, f interface{}, server *chanrpc.Server) { //判断命令是否存在 for _, c := range commands { if c.name() == name { log.Fatal("command %v is already registered", name) } } //注册f(函数) server.Register(name, f) //将命令注册进RPC服务器内 c := new(ExternalCommand) //创建一个外部命令 c._name = name //保存命令名字 c._help = help //保存命令帮助 c.server = server //保存命令服务(一个rpc服务器) commands = append(commands, c) //添加命令到命令列表中 }
func Run(mods ...module.Module) { // logger if conf.LogLevel != "" { logger, err := log.New(conf.LogLevel, conf.LogPath) if err != nil { panic(err) } log.Export(logger) defer logger.Close() } log.Release("Leaf starting up") // profile if conf.EnableProfiling { now := time.Now() filename := fmt.Sprintf("%d%02d%02d_%02d_%02d_%02d.prof", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second()) f, err := os.Create(path.Join(conf.ProfilePath, filename)) if err != nil { log.Fatal("%v", err) } pprof.StartCPUProfile(f) defer pprof.StopCPUProfile() } // module for i := 0; i < len(mods); i++ { module.Register(mods[i]) } module.Init() // close c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, os.Kill) sig := <-c log.Release("Leaf closing down (signal: %v)", sig) module.Destroy() }
func (m *Module) OnInit() { m.TCPGate = &gate.TCPGate{ Addr: conf.Server.Addr, MaxConnNum: conf.Server.MaxConnNum, PendingWriteNum: conf.PendingWriteNum, LenMsgLen: conf.LenMsgLen, MinMsgLen: conf.MinMsgLen, MaxMsgLen: conf.MaxMsgLen, LittleEndian: conf.LittleEndian, AgentChanRPC: game.ChanRPC, } switch conf.Encoding { case "json": m.TCPGate.JSONProcessor = msg.JSONProcessor case "protobuf": m.TCPGate.ProtobufProcessor = msg.ProtobufProcessor default: log.Fatal("unknown encoding: %v", conf.Encoding) } }