Esempio n. 1
0
func (s *Server) Close() {
	if err := s.dao.Close(); err != nil {
		log.Error(err.Error())
	}
	for _, v := range s.agents {
		if err := v.Close(); err != nil {
			log.Error(err.Error())
		}
	}
}
Esempio n. 2
0
func (a *Agent) Serve() (err error) {
	a.Enter()
	defer a.Exit()

	session := make(chan string, 5)
	go func(c chan string) {
		var buf string
		for {
			err = a.Read(&buf)
			if err != nil {
				//fixme: 通过正常流程退出
				log.Debug("agent read: ", err.Error())
				return
			}
			c <- buf
		}
	}(session)

	timeout := time.NewTimer(0)
L:
	for {
		timeout.Reset(10 * time.Second)
		select {

		case cmd := <-a.out:
			if cmd == CtrlRemoveAgent {
				log.Debug("recv ctrl: CtrlRemoveAgent")
				break L
			}

		case msg := <-session:
			var resp string
			resp, err = a.Handle(msg)
			if err != nil {
				log.Error("agent session: ", err.Error())
				break L
			}
			a.Write(resp)

		case msg := <-a.send:
			if err = a.Write(msg); err != nil {
				// 写错误
				log.Error("client write failed: ", err.Error())
				break L
			}

		case <-timeout.C:
			log.Debug("recv timeout")
			break L

		}
	}

	return
}
Esempio n. 3
0
func sendMsg(conn *websocket.Conn, msg string) (err error) {
	if _, err = conn.Write([]byte(msg)); err != nil {
		log.Error(err.Error())
		return
	}
	var rec string
	if err = websocket.Message.Receive(conn, &rec); err != nil {
		log.Error(err.Error())
		return
	}
	return
}
Esempio n. 4
0
/**
 * generate external command file for client using
 */
func GenCommandOutput(path string) {
	var buf bytes.Buffer

	for i := Cmd_Com_Start; i <= Cmd_Com_End; i++ {
		fmt.Fprintf(&buf, "%v = %d\n", i, i)
	}
	fmt.Fprint(&buf, "\n")

	for i := Cmd_Ag_Start; i <= Cmd_Ag_End; i++ {
		fmt.Fprintf(&buf, "%v = %d\n", i, i)
	}
	fmt.Fprint(&buf, "\n")

	for i := Cmd_Game_Start; i <= Cmd_Game_End; i++ {
		fmt.Fprintf(&buf, "%v = %d\n", i, i)
	}
	fmt.Fprint(&buf, "\n")

	for i := Cmd_Cow_Start; i <= Cmd_Cow_End; i++ {
		fmt.Fprintf(&buf, "%v = %d\n", i, i)
	}

	err := ioutil.WriteFile(filepath.Join(path, "cmd.txt"), buf.Bytes(), 0666) //写入文件(字节数组)
	if err != nil {
		log.Error(err)
	}
}
Esempio n. 5
0
func NewServer() (*Server, error) {
	// connect dao server
dao:
	daocli, err := rpc.Dial("tcp", cfg.DaoAddr())
	if err != nil {
		log.Warningf("dao server connect fail(err=%+v), try again...", err.Error())
		time.Sleep(1 * time.Second)
		goto dao
	}

	ctrl := make(chan string, 10)
game:
	cli, err := fw.NewClient(cfg.GameAddr(), &gameCliModel{}, ctrl)
	if err != nil {
		log.Error(err.Error())
		log.Warningf("game server connect fail(err=%+v), try again...", err.Error())
		time.Sleep(1 * time.Second)
		goto game
	}
	go cli.Loop()

	// daemon routine (to be done), with "ctrl"
	// ......
	////////////////////

	// new server
	serverInst = &Server{
		dao:       daocli,
		gameCli:   cli,
		gameCtrl:  ctrl,
		connIdAcc: 0,
		agents:    make(map[int]*fw.Agent, 1000),
	}
	return serverInst, nil
}
Esempio n. 6
0
func NewUser(p *Models) *User {
	u := new(User)
	c, err := redis.Dial("tcp", cfg.RedisAddr(),
		redis.DialReadTimeout(1*time.Second), redis.DialWriteTimeout(1*time.Second))
	if err != nil {
		log.Error(err.Error())
		return nil
	}
	u.c = c

	//select db
	s, err := c.Do("SELECT", cfg.RedisDBs[cfg.Pf])
	if err != nil {
		log.Error(err.Error())
		return nil
	}
	//temp
	fw.PrintType(s, "s")

	//fill keys
	b, _ := redis.Bool(c.Do("EXISTS", k_account_count))

	//	switch b.(type) {
	//	case interface{}:
	//		log..Debug("interface")
	//	case []byte:
	//		log..Debug("byte")
	//	case string:
	//		log..Debug("string")
	//	case *int:
	//		log..Debug("int")
	//	default:
	//		log..Debug("other")
	//	}

	if b == false {
		c.Do("SET", k_account_count, 0)
		log.Info("fill key:", k_account_count)
	}

	//register model
	u.parent = p
	return u
}
Esempio n. 7
0
func (g *Game) genLoginKey(id string) (key string) {
	log.Infof("game:genLoginKey, g=%+v", g)
	key = strconv.Itoa(fw.FastRand())
	log.Debugf("%+v, %+v", g, g.c)
	_, err := g.c.Do("HSET", LoginkeyKey, id, key)
	if err != nil {
		log.Error(err.Error())
	}
	return
}
Esempio n. 8
0
func (c *card) score() int {
	if c.n < cn_1 {
		log.Error("c.n is invalid(<1)")
	}
	if c.n < cn_10 {
		return int(c.n)
	} else {
		return 10
	}
}
Esempio n. 9
0
func (m *model) handleToGame(content string) (resp string, err error) {
	req := &ToRoomReq{Id: m.id, Content: content}
	var b []byte
	if b, err = json.Marshal(req); err != nil {
		log.Error("handleToGame:error=", err)
	}
	msg := com.MakeConnIdRawMsgString(m.agent.ConnId, b) // can? b is of []type, need string
	serverInst.gameCli.Send(msg)
	return
}
Esempio n. 10
0
func startServer2() {
	server, err := NewServer()
	if err != nil {
		log.Error(err.Error())
		return
	}
	defer func() {
		server.Close()
	}()

	serve := func(ws *websocket.Conn) {
		log.Debug("new agent")
		if err := server.Serve(fw.NewWsReadWriter(ws)); err != nil {
			log.Error(err.Error())
		}
		log.Debug("agent leave")
	}

	http.Handle("/", websocket.Handler(serve))
	http.ListenAndServe(cfg.AgentAddr(), nil)
	log.Info("server2 serve on ", cfg.AgentAddr())
}
Esempio n. 11
0
func (c *Client) Loop() (err error) {
	defer func() {
		c.ctrl <- ClientReturn
	}()

	session := make(chan string, 1)
	go func(ch chan string) {
		var buf string
		for {
			err = c.Read(&buf)
			if err != nil {
				log.Error("client read failed: ", err.Error())
				return
			}
			ch <- buf
		}
	}(session)

	for {
		select {
		case cmd := <-c.ctrl:
			if cmd == CtrlRemoveAgent {
				return
			}
		case msg := <-session:
			err = c.Handle(msg)
			if err != nil {
				log.Error("client handle failed: ", err.Error())
				return
			}
		case msg := <-c.send:
			if err = c.Write(msg); err != nil {
				// 写错误
				log.Error("client write failed: ", err.Error())
				return
			}
		}
	}
}
Esempio n. 12
0
func NewGame(p *Models) *Game {
	g := new(Game)
	c, err := redis.Dial("tcp", cfg.RedisAddr(),
		redis.DialReadTimeout(1*time.Second), redis.DialWriteTimeout(1*time.Second))
	if err != nil {
		log.Error(err.Error())
		return nil
	}
	g.c = c

	//select db
	_, err = c.Do("SELECT", cfg.RedisDBs[cfg.Game])
	if err != nil {
		log.Error(err.Error())
		return nil
	}

	//register model
	g.parent = p

	return g
}
Esempio n. 13
0
func (c *Clientmodel) Handle(req string) (err error) {
	var msg com.Msg
	if err = json.Unmarshal([]byte(req), &msg); err != nil {
		log.Error("Unmarshal err: ", err)
		return
	}

	switch msg.Cmd {
	case com.Cmd_Ag_RegisterResp:
		err = c.handleRegister(msg.Content)
	case com.Cmd_Ag_AuthResp:
		err = c.handleAuth(msg.Content)
	case com.Cmd_Ag_LoginResp:
		err = c.handleLogin(msg.Content)
	case com.Cmd_Ag_InfoResp:
		err = c.handleInfo(msg.Content)
	}
	if err != nil {
		log.Error("handle err: ", err.Error())
	}
	return
}
Esempio n. 14
0
func (m *gameCliModel) Handle(req string) (err error) {
	var msg com.ConnIdRawMsg
	if err = json.Unmarshal([]byte(req), &msg); err != nil {
		log.Error("Unmarshal err: ", err)
		return
	}

	agent := serverInst.GetAgent(msg.ConnId)
	if agent != nil {
		agent.Send(msg.Content)
	} else {
		err = com.ErrAgentNotFound
	}
	return
}
Esempio n. 15
0
func TestServer2(t *testing.T) {
	go func() {
		once.Do(startServer2)
	}()

	//	time.Sleep(5 * time.Second)

	conn, err := newClient()
	defer conn.Close()

	if err != nil {
		log.Error("newClient: ", err.Error())
		return
	}

	var msg string

	//	log.Info("test:register")
	//	msg = []byte(`{"cmd":100,
	//		"content":"{\"account\":\"testUtf\",\"psw\":\"pswlk22\"}"
	//		}`)
	//	sendMsg(conn, msg)
	//	time.Sleep(1 * time.Second)

	log.Info("test:cmdLoginReq1")
	//	msg = []byte(`{"cmd":104,"content":"{\"account\":\"testUtf\",\"psw\":\"pswlk22\"}"}`)
	msg = com.MakeMsgString(com.Cmd_Ag_LoginReq, 0, &LoginReq{"testUtf", "pswlk22"})
	sendMsg(conn, msg)
	time.Sleep(1 * time.Second)

	//	log.Info("test:cmdLoginReq2")
	//	msg = []byte(`{"cmd":104,"content":"{\"account\":\"testUtf\",\"psw\":\"p\"}"}`)
	//	sendMsg(conn, msg)
	//	time.Sleep(1 * time.Second)

	log.Info("test:handleInfo")
	//	msg = []byte(`{"cmd":106}`)
	//	msg = []byte(`{"cmd":106,"content":"{\"account\":\"testUtf\",\"psw\":\"p\"}"}`)
	msg = com.MakeMsgString(com.Cmd_Ag_InfoReq, 0, nil)
	sendMsg(conn, msg)
	time.Sleep(11 * time.Second)

	log.Info("test:enter game room")
	msg = com.MakeMsgString(com.Cmd_Ag_ToGameReq, 0, nil)

}
Esempio n. 16
0
func (m *model) handleRegister(content string) (resp string, err error) {
	//	daocli.
	var req RegisterReq
	if err = json.Unmarshal([]byte(content), &req); err != nil {
		log.Error("content=", content, ", err: ", err.Error())
		return
	}
	args := &dao.User_RegisterArgs{req.Account, req.Psw}
	var reply dao.Reply
	log.Debugf("req : %#v", req)
	//	if err = h.dc.UserRegister(&args, &reply); err != nil {
	if err = m.dao.Call("User.Register", args, &reply); err != nil {
		return
	}
	log.Infof("User.Register %+v -> %+v", args, reply)
	resp = com.MakeMsgString(com.Cmd_Ag_RegisterResp, reply.Code, nil)
	return
}
Esempio n. 17
0
func main() {
	server, err := agent.NewServer()
	if err != nil {
		panic("new server failed")
	}
	defer func() {
		server.Close()
	}()

	serve := func(ws *websocket.Conn) {
		if err := server.Serve(fw.NewWsReadWriter(ws)); err != nil {
			log.Error(err.Error())
		}
		log.Infof("agent leaves, agent count=%v", server.AgentCount())
	}

	http.Handle("/", websocket.Handler(serve))
	log.Debug("agent server start on:", cfg.AgentPort)
	http.ListenAndServe(":"+cfg.AgentPort, nil)
}
Esempio n. 18
0
func main() {
	var agent *fw.Agent
	serve := func(ws *websocket.Conn) {
		// only ONE agent server allowed to connect
		log.Debugf("new comes, agent=%+v", agent)
		if agent == nil {
			agent = fw.NewAgent(game.NewModel(), fw.NewWsReadWriter(ws), 1)
			if err := agent.Serve(); err != nil {
				log.Error(err.Error())
			}
		} else {
			log.Warning("already connected by agentsrv, cannont serve more")
		}
		// release
		agent = nil
	}

	http.Handle("/", websocket.Handler(serve))
	log.Debug("game server start on:", cfg.GameAddr())
	http.ListenAndServe(cfg.GameAddr(), nil)

}