Exemple #1
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()
	}

}
Exemple #2
0
/**
创建角色
name	角色名
pic		角色头像/avatar
*/
func CreatePlayer(session *server.Session, response *server.Response, request server.Request) {
	//

	name, hasName := request.Get("name")
	pic, hasPic := request.Get("pic")

	if !hasName || !hasPic {
		response.Put("state", server.STATE_FAILD)
		response.Put("msg", "参数错误!")
		return
	}

	var userId int
	if v, err := session.Get(server.ATTR_USER_ID); err != nil {
		response.Put("state", server.STATE_FAILD)
		response.Put("msg", "找不到userid!")
		return
	} else {
		userId = v.(int)
	}

	err := world.WPlayerService.CreatePlayer(name, userId, pic)
	if err != nil {
		utils.CheckErr(err)
		response.Put("state", server.STATE_FAILD)
		response.Put("msg", "程序执行错误!")
		return
	}

	response.Put("state", server.STATE_OK)
}
Exemple #3
0
/*
 *	初始化数据库链接池
 */
func InitPgSqlPool() bool {
	pool_size, _ := utils.Config.GetInt("database", "max_connection")
	user, _ := utils.Config.GetString("database", "user")
	pwd, _ := utils.Config.GetString("database", "password")
	dbname, _ := utils.Config.GetString("database", "db")

	Pool = new(PgSqlPool)
	Pool.MaxPoolSize = pool_size
	Pool.User = user
	Pool.Password = pwd
	Pool.Dbname = dbname
	Pool.ConnPool = make(chan *sql.DB, Pool.MaxPoolSize)

	go func() {
		for i := 0; i < Pool.MaxPoolSize; i++ {
			var err error
			var conn *sql.DB
			dataSourceName := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", Pool.User, Pool.Password, Pool.Dbname)
			conn, err = sql.Open("postgres", dataSourceName)
			utils.CheckErr(err)

			PutPgSql(conn)
		}
	}()

	return true
}
Exemple #4
0
/*
session 循环
*/
func (session *Session) SessionLoop() {
	defer session.Conn.Close()
	//处理连接建立
	session.CreateConnection()

	for {
		//从socket接受数据
		data, err := bufio.NewReader(session.Conn).ReadString('\n')

		if err != nil {
			if err == io.EOF {
				Smgr.Remove(session.Id) //移除sesssion
				session.Disconnected()  //链接断开
				break

			}
			utils.CheckErr(err)
			break

		}

		data = data[0 : len(data)-1] //去除最后的换行字符
		session.HandleReceive(data)
	}

}
Exemple #5
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)

}
Exemple #6
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())

}
Exemple #7
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)

}
Exemple #8
0
func initDatabases() bool {
	//	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")

	dataSourceName := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", user, pwd, dbname)
	db, err := sql.Open("postgres", dataSourceName)
	utils.CheckErr(err)

	beedb.New(db, "pq")
	return true
}
Exemple #9
0
/**
登录帐号
name	帐号
pwd		密码
*/
func UserLogin(session *server.Session, response *server.Response, request server.Request) {
	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()

	userId, err := tx.QueryUser(name, pwd)
	if err != nil {
		utils.CheckErr(err)
		response.Put("state", server.STATE_FAILD)
		response.Put("msg", "程序执行异常!")
		return
	}

	// 帐号不存在,或者密码错误
	if userId == 0 {
		response.Put("state", server.STATE_FAILD)
		response.Put("msg", "请检查帐号密码是否正确!")
		return
	}

	// 帐号检查成功
	// 存储userId
	session.Put(server.ATTR_USER_ID, userId)
	//
	session.Put(server.ATTR_IS_LOGIN, true)

	response.Put("state", server.STATE_OK)
}