Ejemplo n.º 1
0
func rpcUserLogin(args []interface{}) {
	a := args[0].(gate.Agent)
	accID := args[1].(int64)

	// network closed
	if a.UserData() == nil {
		return
	}

	// login repeated
	oldSession := accIDSessions[accID]
	if oldSession != nil {
		m := &msg.ClosePush{Code: msg.ClosePush_REPEATED.Enum()}
		a.WriteMsg(m)
		a.Close()
		oldSession.WriteMsg(m)
		oldSession.Close()
		log.Debug("acc %v login repeated", accID)
		return
	}

	log.Debug("acc %v login", accID)

	// login
	newSession := new(Session)
	newSession.Agent = a
	newSession.LinearContext = skeleton.NewLinearContext()
	newSession.state = Session_Login
	a.UserData().(*AgentInfo).accID = accID
	accIDSessions[accID] = newSession

	newSession.login(accID)
}
Ejemplo n.º 2
0
func (a *TCPAgent) Run() {
	for {
		data, err := a.conn.ReadMsg()
		if err != nil {
			log.Debug("read message error: %v", err)
			break
		}

		if a.gate.JSONProcessor != nil {
			// json
			msg, err := a.gate.JSONProcessor.Unmarshal(data)
			if err != nil {
				log.Debug("unmarshal json error: %v", err)
				break
			}
			err = a.gate.JSONProcessor.Route(msg, Agent(a))
			if err != nil {
				log.Debug("route message error: %v", err)
				break
			}
		} else if a.gate.ProtobufProcessor != nil {
			// protobuf
			msg, err := a.gate.ProtobufProcessor.Unmarshal(data)
			if err != nil {
				log.Debug("unmarshal protobuf error: %v", err)
				break
			}
			err = a.gate.ProtobufProcessor.Route(msg, Agent(a))
			if err != nil {
				log.Debug("route message error: %v", err)
				break
			}
		}
	}
}
Ejemplo n.º 3
0
//实现代理接口(network.Agent)Run函数
func (a *TCPAgent) Run() {
	for {
		data, err := a.conn.ReadMsg() //读取一条完整的消息
		if err != nil {
			log.Debug("read message error: %v", err)
			break
		}

		if a.gate.JSONProcessor != nil { //配置为使用JSON处理
			// json
			msg, err := a.gate.JSONProcessor.Unmarshal(data) //解码JSON数据
			if err != nil {
				log.Debug("unmarshal json error: %v", err)
				break
			}
			err = a.gate.JSONProcessor.Route(msg, Agent(a)) //分发数据,将a转化成Agent作为用户数据
			if err != nil {
				log.Debug("route message error: %v", err)
				break
			}
		} else if a.gate.ProtobufProcessor != nil { //配置为使用protobuf处理
			// protobuf
			msg, err := a.gate.ProtobufProcessor.Unmarshal(data) //解码protobuf数据
			if err != nil {
				log.Debug("unmarshal protobuf error: %v", err)
				break
			}
			err = a.gate.ProtobufProcessor.Route(msg, Agent(a)) //分发数据
			if err != nil {
				log.Debug("route message error: %v", err)
				break
			}
		}
	}
}
Ejemplo n.º 4
0
func rpcUserLogin(args []interface{}) {
	a := args[0].(gate.Agent)
	accID := args[1].(string)

	// network closed
	if a.UserData() == nil {
		return
	}

	// login repeated
	oldUser := accIDUsers[accID]
	if oldUser != nil {
		m := &msg.S2C_Close{Err: msg.S2C_Close_LoginRepeated}
		a.WriteMsg(m)
		oldUser.WriteMsg(m)
		a.Close()
		oldUser.Close()
		log.Debug("acc %v login repeated", accID)
		return
	}

	log.Debug("acc %v login", accID)

	// login
	newUser := new(User)
	newUser.Agent = a
	newUser.LinearContext = skeleton.NewLinearContext()
	newUser.state = userLogin
	a.UserData().(*AgentInfo).accID = accID
	accIDUsers[accID] = newUser

	newUser.login(accID)
}
Ejemplo n.º 5
0
func rpcCloseAgent(args []interface{}) {
	log.Debug("CloseAgent.....")
	a := args[0].(gate.Agent)
	_ = a
	userdata := a.UserData()
	if userdata != nil {
		name := userdata.(string)
		delete(AgentMap, name)
		for _, v := range manager.roomList {
			log.Debug("%s left room%d", name, v.id)
			manager.Leave(v.id, name)
		}
	}

}
Ejemplo n.º 6
0
func handleLogin(args []interface{}) {
	log.Debug("handleLogin")
	m := args[0].(*msg.Login)
	a := args[1].(gate.Agent)
	id := GetUniqId()
	username := fmt.Sprintf("%s%d", "user", id)
	a.SetUserData(username)
	log.Debug("Set Agent Map %s", username)
	AgentMap[username] = a

	log.Debug("%s Logged in", m.Request.S_name)
	var r msg.Login
	r.Response.S_name = username
	r.Response.I_code = 0
	a.WriteMsg(&r)
}
Ejemplo n.º 7
0
func (p *RoomManager) Join(id int, name string) (err error) {
	room, e := p.whereAmI(name)
	if e == nil {
		err = errors.New(fmt.Sprintf("already in room:%d", room.id))
		return
	}
	p.Lock()
	defer p.Unlock()
	for _, v := range p.roomList {
		log.Debug("checking room %d", v.id)
		if v.id == id {

			if v.players.Len() < v.max {
				//ok. player can join
				v.players.Add(name)
				return nil
			} else {
				err = errors.New("room full")
				return
			}
		}
	}
	err = errors.New("no such room")
	return
}
Ejemplo n.º 8
0
func (tcpConn *TCPConn) doWrite(b []byte) {
	if len(tcpConn.writeChan) == cap(tcpConn.writeChan) {
		log.Debug("close conn: channel full")
		tcpConn.doDestroy()
		return
	}

	tcpConn.writeChan <- b
}
Ejemplo n.º 9
0
//做写操作
func (tcpConn *TCPConn) doWrite(b []byte) {
	if len(tcpConn.writeChan) == cap(tcpConn.writeChan) { //如果发送缓冲区的长度等于最大容量
		log.Debug("close conn: channel full") //日志记录,管道已满
		tcpConn.doDestroy()                   //做销毁操作
		return
	}

	tcpConn.writeChan <- b //将待发数据发送到发送缓冲区
}
Ejemplo n.º 10
0
func (wsConn *WSConn) doWrite(b []byte) {
	if len(wsConn.writeChan) == cap(wsConn.writeChan) {
		log.Debug("close conn: channel full")
		wsConn.doDestroy()
		return
	}

	wsConn.writeChan <- b
}
Ejemplo n.º 11
0
func handleRoomList(args []interface{}) {
	m := args[0].(*msg.RoomListReq)
	a := args[1].(*Session)
	log.Debug("%v", m, a)
	res := &msg.RoomListRes{}
	for _, v := range roomIdRooms {
		res.Rooms = append(res.Rooms, &msg.RoomListRes_RoomInfo{Id: proto.Int32(v.Id), PlayerNum: proto.Int32(int32(len(v.players)))})
	}

}
Ejemplo n.º 12
0
Archivo: gate.go Proyecto: haoqoo/leaf
func (a *agent) Run() {
	for {
		var (
			data []byte
			err  error
		)
		if a.wsConn != nil {
			data, err = a.wsConn.ReadMsg()
		} else if a.tcpConn != nil {
			data, err = a.tcpConn.ReadMsg()
		}
		if err != nil {
			log.Debug("read message: %v", err)
			break
		}

		if a.gate.JSONProcessor != nil {
			// json
			msg, err := a.gate.JSONProcessor.Unmarshal(data)
			if err != nil {
				log.Debug("unmarshal json error: %v", err)
				break
			}
			err = a.gate.JSONProcessor.Route(msg, a)
			if err != nil {
				log.Debug("route message error: %v", err)
				break
			}
		} else if a.gate.ProtobufProcessor != nil {
			// protobuf
			msg, err := a.gate.ProtobufProcessor.Unmarshal(data)
			if err != nil {
				log.Debug("unmarshal protobuf error: %v", err)
				break
			}
			err = a.gate.ProtobufProcessor.Route(msg, a)
			if err != nil {
				log.Debug("route message error: %v", err)
				break
			}
		}
	}
}
Ejemplo n.º 13
0
func (a *agent) Run() {
	for {
		data, err := a.conn.ReadMsg()
		if err != nil {
			log.Debug("read message: %v", err)
			break
		}

		if a.gate.Processor != nil {
			msg, err := a.gate.Processor.Unmarshal(data)
			if err != nil {
				log.Debug("unmarshal message error: %v", err)
				break
			}

			a.gate.Processor.Route(msg, a)
		}
	}
}
Ejemplo n.º 14
0
func (handler *WSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		return
	}
	conn, err := handler.upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Debug("upgrade error: %v", err)
		return
	}
	conn.SetReadLimit(int64(handler.maxMsgLen))

	handler.wg.Add(1)
	defer handler.wg.Done()

	handler.mutexConns.Lock()
	if handler.conns == nil {
		handler.mutexConns.Unlock()
		conn.Close()
		return
	}
	if len(handler.conns) >= handler.maxConnNum {
		handler.mutexConns.Unlock()
		conn.Close()
		log.Debug("too many connections")
		return
	}
	handler.conns[conn] = struct{}{}
	handler.mutexConns.Unlock()

	wsConn := newWSConn(conn, handler.pendingWriteNum, handler.maxMsgLen)
	agent := handler.newAgent(wsConn)
	agent.Run()

	// cleanup
	wsConn.Destroy()
	handler.mutexConns.Lock()
	delete(handler.conns, conn)
	handler.mutexConns.Unlock()
	agent.OnClose()
}
Ejemplo n.º 15
0
func handleRegister(args []interface{}) {
	m := args[0].(*msg.RegisterReq)
	a := args[1].(gate.Agent)
	log.Debug("%v", m, a)
	account := new(model.Account)
	account.Name = m.GetName()
	account.Password = m.GetPassword()
	affected, err := model.Engine.Insert(account)
	if err != nil {
		//所有错误都返回用户名已存在
		log.Error("%v", err)
		a.WriteMsg(&msg.RegisterRes{Code: msg.RegisterRes_EXIST.Enum()})
		return
	}
	log.Debug("%v", affected)
	if affected == 1 {
		a.WriteMsg(&msg.RegisterRes{Code: msg.RegisterRes_YES.Enum()})
	} else {
		a.WriteMsg(&msg.RegisterRes{Code: msg.RegisterRes_NO.Enum()})
	}
}
Ejemplo n.º 16
0
func (server *TCPServer) run() {
	server.wgLn.Add(1)
	defer server.wgLn.Done()

	var tempDelay time.Duration
	for {
		conn, err := server.ln.Accept()
		if err != nil {
			if ne, ok := err.(net.Error); ok && ne.Temporary() {
				if tempDelay == 0 {
					tempDelay = 5 * time.Millisecond
				} else {
					tempDelay *= 2
				}
				if max := 1 * time.Second; tempDelay > max {
					tempDelay = max
				}
				log.Release("accept error: %v; retrying in %v", err, tempDelay)
				time.Sleep(tempDelay)
				continue
			}
			return
		}
		tempDelay = 0

		server.mutexConns.Lock()
		if len(server.conns) >= server.MaxConnNum {
			server.mutexConns.Unlock()
			conn.Close()
			log.Debug("too many connections")
			continue
		}
		server.conns[conn] = struct{}{}
		server.mutexConns.Unlock()

		server.wgConns.Add(1)

		tcpConn := newTCPConn(conn, server.PendingWriteNum, server.msgParser)
		agent := server.NewAgent(tcpConn)
		go func() {
			agent.Run()

			// cleanup
			tcpConn.Destroy()
			server.mutexConns.Lock()
			delete(server.conns, conn)
			server.mutexConns.Unlock()
			agent.OnClose()

			server.wgConns.Done()
		}()
	}
}
Ejemplo n.º 17
0
func handleLogin(args []interface{}) {
	m := args[0].(*msg.LoginReq)
	a := args[1].(gate.Agent)
	log.Debug("%v", m, a)
	account := &model.Account{Name: m.GetName()}
	has, err := model.Engine.Get(account)
	if err != nil {
		a.WriteMsg(&msg.LoginRes{Code: msg.LoginRes_NO.Enum()})
		return
	}
	log.Debug("%v", account)
	if has {
		if account.Password != m.GetPassword() {
			a.WriteMsg(&msg.LoginRes{Code: msg.LoginRes_PASS_ERR.Enum()})
		} else {
			a.WriteMsg(&msg.LoginRes{Code: msg.LoginRes_YES.Enum()})
			game.ChanRPC.Go("UserLogin", a, account.Id)
		}
	} else {
		a.WriteMsg(&msg.LoginRes{Code: msg.LoginRes_NOT_EXIST.Enum()})
	}
}
Ejemplo n.º 18
0
func Example() {
	name := "Leaf"

	log.Debug("My name is %v", name)
	log.Release("My name is %v", name)
	log.Error("My name is %v", name)
	// log.Fatal("My name is %v", name)

	logger, err := log.New("release", "")
	if err != nil {
		return
	}
	defer logger.Close()

	logger.Debug("will not print")
	logger.Release("My name is %v", name)

	log.Export(logger)

	log.Debug("will not print")
	log.Release("My name is %v", name)
}
Ejemplo n.º 19
0
func handleHello(args []interface{}) {
	// 收到的 Hello 消息
	m := args[0].(*msg.Hello)
	// 消息的发送者
	a := args[1].(gate.Agent)

	// 输出收到的消息的内容
	log.Debug("hello %v", m.Name)

	// 给发送者回应一个 Hello 消息
	a.WriteMsg(&msg.Hello{
		Name: "client",
	})
}
Ejemplo n.º 20
0
func handleHello(args []interface{}) {
	// 收到的 Hello 消息
	m := args[0].(*msg.Hello)
	// 消息的发送者
	a := args[1].(gate.Agent)
	a.SetUserData(m.Request.S_name)
	// 输出收到的消息的内容
	log.Debug("hello %+v", m)

	// 给发送者回应一个 Hello 消息
	var t msg.Hello
	t.Request.S_name = "abc"
	//t.Response.S_name = "def"
	a.WriteMsg(&t)
}
Ejemplo n.º 21
0
func handleActivity(args []interface{}) {
	m := args[0].(*msg.Activity)
	a := args[1].(gate.Agent)
	name := a.UserData().(string)
	room, err := manager.whereAmI(name)
	log.Debug("Get Parameter:%+v", m)

	if err == nil {
		var gameinfo msg.GameInfo
		gameinfo.I_green_pos_x = m.Request.I_green_pos_x
		gameinfo.I_green_pos_y = m.Request.I_green_pos_y
		gameinfo.I_grey_pos_x = m.Request.I_grey_pos_x
		gameinfo.I_grey_pos_y = m.Request.I_grey_pos_y
		gameinfo.S_name = name
		room.players_data[name] = gameinfo
		log.Debug("updating gameinfo %s===%+v", name, gameinfo)
	} else {
		//var r msg.Activity
		//		r.Response.S_name = name
		//		r.Response.I_code = 1
		//		r.Response.S_text = err.Error()
		//		log.Debug(err.Error())
	}
}
Ejemplo n.º 22
0
// goroutine safe
func (s *Server) Go(id interface{}, args ...interface{}) {
	f := s.functions[id]
	if f == nil {
		log.Debug("没有绑定处理函数:  %v", id)
		return
	}

	defer func() {
		recover()
	}()

	s.ChanCall <- &CallInfo{
		f:    f,
		args: args,
	}
}
Ejemplo n.º 23
0
func handleJoin(args []interface{}) {
	m := args[0].(*msg.Join)
	a := args[1].(gate.Agent)
	name := a.UserData().(string)
	log.Debug("%s wants to join room %d", name, m.Request.I_no)
	err := manager.Join(m.Request.I_no, name)

	var r msg.Join
	if err == nil {
		r.Response.I_code = 0
	} else {
		r.Response.I_code = 1
		r.Response.S_text = err.Error()
	}

	a.WriteMsg(&r)
}
Ejemplo n.º 24
0
//运行TCP服务器
func (server *TCPServer) run() {
	for { //死循环
		conn, err := server.ln.Accept() //接受一个连接
		if err != nil {                 //如果有错(如果调用了server.Close,再Accept,那么就会出错)
			if server.closeFlag { //服务器关闭标志为true 因为关闭了TCP服务器导致的出错
				return //结束循环
			} else {
				log.Error("accept error: %v", err) //日志记录接受连接出错
				continue                           //继续循环
			}
		}

		server.mutexConns.Lock()                    //加锁,为什么要加锁,因为会从不同的goroutine中访问server.conns,比如从外部goroutine中调用server.Close或者在新的goroutine中运行代理执行清理工作的时候或者当前for循环所在goroutine中增加连接记录
		if len(server.conns) >= server.MaxConnNum { //如果当前连接数超过上限
			server.mutexConns.Unlock()        //解锁
			conn.Close()                      //关闭新来的连接
			log.Debug("too many connections") //日志记录:太多连接了
			continue                          //继续循环
		}
		//增加连接记录
		server.conns[conn] = struct{}{} //struct{}为类型,第二个{}为初始化,只不过是空值而已
		server.mutexConns.Unlock()      //解锁

		server.wg.Add(1) //等待组+1

		tcpConn := newTCPConn(conn, server.PendingWriteNum, server.msgParser) //创建一个TCP连接(原有net.Conn的封装)
		agent := server.NewAgent(tcpConn)                                     //调用注册的创建代理函数创建代理
		go func() {                                                           //此处形成闭包
			agent.Run() //在一个新的goroutine中运行代理,一个客户端一个agent
			//执行到这里时agent.Run for循环结束
			// cleanup
			//清理工作
			tcpConn.Close()            //关闭连接(封装层)
			server.mutexConns.Lock()   //加锁
			delete(server.conns, conn) //从连接集合中删除连接
			server.mutexConns.Unlock() //解锁
			agent.OnClose()            //关闭代理

			server.wg.Done() //等待组-1
		}()
	}
}
Ejemplo n.º 25
0
func rpcCloseAgent(args []interface{}) {
	a := args[0].(gate.Agent)

	accID := a.UserData().(*AgentInfo).accID
	a.SetUserData(nil)

	session := accIDSessions[accID]
	if session == nil {
		return
	}

	log.Debug("acc %v logout", accID)

	// logout
	if session.state == Session_Login { //还在登录中
		session.state = Session_Logout //仅仅设置标志,待登录完成执行logout操作
	} else {
		session.state = Session_Logout
		session.logout(accID)
	}
}
Ejemplo n.º 26
0
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,
	}
	log.Debug("Gate:Oninit")
	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)
	}
}
Ejemplo n.º 27
0
func rpcCloseAgent(args []interface{}) {
	a := args[0].(gate.Agent)

	accID := a.UserData().(*AgentInfo).accID
	a.SetUserData(nil)

	user := accIDUsers[accID]
	if user == nil {
		return
	}

	log.Debug("acc %v logout", accID)

	// logout
	if user.state == userLogin {
		user.state = userLogout
	} else {
		user.state = userLogout
		user.logout(accID)
	}
}
Ejemplo n.º 28
0
func (server *TCPServer) run() {
	for {
		conn, err := server.ln.Accept()
		if err != nil {
			if server.closeFlag {
				return
			} else {
				log.Error("accept error: %v", err)
				continue
			}
		}

		server.mutexConns.Lock()
		if len(server.conns) >= server.MaxConnNum {
			server.mutexConns.Unlock()
			conn.Close()
			log.Debug("too many connections")
			continue
		}
		server.conns[conn] = struct{}{}
		server.mutexConns.Unlock()

		server.wg.Add(1)

		tcpConn := newTCPConn(conn, server.PendingWriteNum, server.msgParser)
		agent := server.NewAgent(tcpConn)
		go func() {
			agent.Run()

			// cleanup
			tcpConn.Close()
			server.mutexConns.Lock()
			delete(server.conns, conn)
			server.mutexConns.Unlock()
			agent.OnClose()

			server.wg.Done()
		}()
	}
}
Ejemplo n.º 29
0
func (p *RoomManager) updateroom(r *Room) {
	players := r.players.List()
	for _, v := range players {

		gameinfo := r.players_data[v]
		for _, v2 := range players {
			if v != v2 {
				agent, ok := AgentMap[v2]
				if ok {
					log.Debug("sending user:%s info to %s content=%+v", v, v2, gameinfo)
					var act msg.Activity
					act.Response.I_code = 0
					act.Response.I_green_pos_x = gameinfo.I_green_pos_x
					act.Response.I_green_pos_y = gameinfo.I_green_pos_y
					act.Response.I_grey_pos_x = gameinfo.I_grey_pos_x
					act.Response.I_grey_pos_y = gameinfo.I_grey_pos_y

					agent.WriteMsg(&act)
				}
			}
		}

	}
}
Ejemplo n.º 30
0
func rpcNewAgent(args []interface{}) {
	log.Debug("NewAgent.....")
	a := args[0].(gate.Agent)
	_ = a

}