Esempio n. 1
0
/*
处理来自客户端的数据
*/
func (session *Session) HandleReceive(data string) {
	logger.Printf("[%d][reveive %d] %s ", session.Id, len(data), data)

	//err := json.Unmarshal([]byte(data), &action)
	as := strings.Split(data, "?")

	// 检测接口是否正确
	if len(as) != 2 {
		logger.Printf("[recv] error action!")
		return
	}

	handlerName := as[0]

	//解析参数
	u, err := ParseArgs(as[1])

	if err != nil {
		utils.CheckErr(err)
		return
	}

	request := Request{}
	request.Args = u
	//设置sessionid
	request.SessionId = session.Id
	if v1, e1 := session.Get(ATTR_USER_ID); e1 == nil {
		//设置userid
		request.UserId = v1.(int)
	}

	if v2, e2 := session.Get(ATTR_PLAYER_ID); e2 == nil {
		//设置playerid
		request.PlayerId = v2.(int)

	}

	// 获取处理函数
	handler, ok := GetHandler(handlerName)
	if !ok {
		logger.Printf("unknow handler --> %s \n", handlerName)
		return
	}

	//执行处理,并返回结果
	response := NewResponse()

	//检查是否登录
	var isLogin = false
	if v, err := session.Get(ATTR_IS_LOGIN); err == nil {
		isLogin = v.(bool)
	}
	if handlerName != "user!regist" && handlerName != "user!login" && !isLogin {
		response.Faild("请先登录!")
	} else {
		handler(session, response, request)
	}
	session.Send(response.Data)

}
Esempio n. 2
0
/*
	注册handler
*/
func RegisterHandler(name string, handler HandlerFunc) {
	if _, ok := handlerMap[name]; !ok {
		logger.Printf("regist action < %s >", name)
		handlerMap[name] = handler
	}

}
Esempio n. 3
0
func CheckErr(err error) {
	if err != nil {
		logger.Printf("Fatal error: %s", err.Error())
		//panic(err.Error())
		//os.Exit(1)
	}
}
Esempio n. 4
0
func (s *Server) Start() {
	//
	serverAddr := fmt.Sprintf("127.0.0.1:%s", s.Port)
	addr, err := net.ResolveTCPAddr("tcp", serverAddr)
	utils.CheckErr(err)

	listener, err := net.Listen("tcp", addr.String())
	utils.CheckErr(err)

	defer listener.Close()

	id := 0

	logger.Printf("start listen addr %s", serverAddr)

	for {
		client, err := listener.Accept()
		if err != nil {
			utils.CheckErr(err)
			continue
		}

		id++ //增加sessionid

		session := NewSession() //新建session
		session.Id = id
		session.Conn = client

		Smgr.Add(session) //将session添加到sessionmanger

		go session.SessionLoop()
	}

}
Esempio n. 5
0
func (smgr *SessionManager) Remove(id int) {
	if _, ok := smgr.sessionMap[id]; ok {
		delete(smgr.sessionMap, id)
	} else {
		logger.Printf("[smgr remove] has no session id (%s)", id)
	}
}
Esempio n. 6
0
func (smgr *SessionManager) Add(session *Session) {
	if _, ok := smgr.sessionMap[session.Id]; ok {
		logger.Printf("[smgr add] has same session id (%s)", session.Id)
	} else {
		smgr.sessionMap[session.Id] = session
	}
}
Esempio n. 7
0
func initDatabases() bool {
	logger.Printf("init databases")
	//	dbHost := gConfig.GetString("database", "host")
	//	dbPort := gConfig.getString("database", "port")
	//	user, _ := utils.Config.GetString("database", "user")
	//	pwd, _ := utils.Config.GetString("database", "password")
	//	dbname, _ := utils.Config.GetString("database", "db")
	//
	//	now := time.Now();
	//	fmt.Printf("当前时间: %v \n", now)
	//	time.Sleep(1 * time.Second)
	//	now = time.Now();
	//	fmt.Printf("当前时间: %v \n", now )
	//	var err error
	//	dataSourceName := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", user, pwd, dbname)
	//	dao.DBconn, err = sql.Open("postgres", dataSourceName )
	//	utils.CheckErr(err)

	//	id := dao.QueryUser("asd", "123")
	//	fmt.Printf("查询玩家:%d\n", id)
	dao.InitPgSqlPool()
	//	for i:=0; i<11; i++ {
	//		userId := dao.QueryUser("test", "123")
	//		fmt.Printf("查询角色(%d): %d\n",i, userId)
	//	}

	return true
}
Esempio n. 8
0
/*
执行查询
*/
func (self *Transaction) Query(sql string, args ...interface{}) (rows *sql.Rows, err error) {
	query_sql := fmt.Sprintf(sql, args...)

	logger.Printf("[query] %s", query_sql)
	/** 从数据库链接池中取出一个链接 **/
	rows, err = self.Tx.Query(query_sql)
	return
}
Esempio n. 9
0
func InitAction() (result bool) {
	logger.Printf("init action")
	server.RegisterHandler("user!regist", RegisterUser)
	server.RegisterHandler("user!login", UserLogin)

	server.RegisterHandler("user!createPlayer", CreatePlayer)
	server.RegisterHandler("user!checkPlayerName", CheckPlayerName)

	result = true
	return
}
Esempio n. 10
0
/**
发送数据到客户端
*/
func (session *Session) Send(msg interface{}) {
	logger.Printf("[%d][send] %v", session.Id, msg)
	data, err := json.Marshal(msg)
	if err != nil {
		utils.CheckErr(err)
		return
	}

	buff := bytes.NewBuffer(data)
	err = buff.WriteByte('\n')
	if err != nil {
		utils.CheckErr(err)
		return
	}
	session.Conn.Write(buff.Bytes())

}
Esempio n. 11
0
/**
注册帐号
name	帐号
pwd		密码
*/
func RegisterUser(session *server.Session, response *server.Response, request server.Request) {
	logger.Printf("regist user: %v", request)
	//dao.CheckUserExist("aa")
	name, hasName := request.Get("name")
	pwd, hasPwd := request.Get("pwd")

	if !hasName || !hasPwd {
		response.Put("state", server.STATE_FAILD)
		response.Put("msg", "参数异常!")
		return
	}

	tx, err := dao.Begin()
	defer tx.Close()

	isExist, err := tx.CheckUserExist(name)

	if err != nil {
		utils.CheckErr(err)
		response.Put("state", server.STATE_FAILD)
		response.Put("msg", "处理异常!")

		return
	}

	if isExist {
		response.Put("state", server.STATE_FAILD)
		response.Put("msg", "帐号已经存在!")

		return
	}

	err = tx.RegistUser(name, pwd)
	if err != nil {
		utils.CheckErr(err)
		response.Put("state", server.STATE_FAILD)
		response.Put("msg", "处理异常!")
		return

	}

	tx.Commit()
	response.Put("state", server.STATE_OK)

}
Esempio n. 12
0
func Start(chStop chan int) {
	chAppStop = chStop

	go func() {
		var sig os.Signal

		signal.Notify(chSignal, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)

		for {
			sig = <-chSignal
			if sig == nil {
				return
			}
			Logger.Printf("Handle Signal: %v", sig)

			switch sig {
			case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGHUP:
				chAppStop <- ErrConf.SIGNAL_ERR
			default:
			}
		}
	}()
}
Esempio n. 13
0
/*
处理来自客户端的数据
*/
func (session *Session) HandleReceive(data string) {
	logger.Printf("[%d][reveive %d] %s ", session.Id, len(data), data)

}
Esempio n. 14
0
/**
断开连接
*/
func (session *Session) Disconnected() {
	logger.Printf("[%d][disconnect] %s", session.Id, session.Conn.RemoteAddr())
}
Esempio n. 15
0
/**
建立连接
*/
func (session *Session) CreateConnection() {
	logger.Printf("[%s][connect] %s ", session.Id, session.Conn.RemoteAddr())
}
Esempio n. 16
0
func (self *Transaction) Exec(sql string, args ...interface{}) (r sql.Result, err error) {
	query_sql := fmt.Sprintf(sql, args...)
	logger.Printf("[insert] %s", query_sql)
	r, err = self.Tx.Exec(query_sql)
	return
}