func (this *WorldServer) HandleClient(session *libnet.Session) { defer waitgroup.Done() defer session.Close() for { msg := new(msgcmd.Cmd) err := session.Receive(msg) if err != nil { println("World Server Error: 接收数据 失败. ", err.Error()) logFile.Printf("World Server Error: 接收数据 失败. ", err.Error()) break } if msg == nil { continue } switch msg.Mid { case msgcmd.MCMD_M2W_REGISTER: this.DoRegister(msg, session) case msgcmd.MCMD_M2W_LOGIN: this.DoLogin(msg, session) case msgcmd.MCMD_M2W_USEROFFLINE: this.DoUserOffline(msg, session) case msgcmd.MCMD_M2W_HEARTBEAT: this.DoHeartBeat(session) case msgcmd.MCMD_M2W_REQUEST_ONLINEUSERS: this.DoRequestOnlineUsers(msg, session) } } }
func (this *MsgServer) HandleClient(session *libnet.Session) { defer waitgroup.Done() //创建一个“匿名用户”,并添加到MS的用户列表中 user := common.NewUserInfo(session) user.MsgChan = make(chan *msgcmd.Cmd, 1024) //插入到用户列表中 this.userlist.Insert(user.Name, user) var isRun bool = true //开一个单独的协程,负责等待Client消息 go func() { for isRun { msg := new(msgcmd.Cmd) if session.IsClosed() { return } err := session.Receive(msg) if err != nil { if err == io.EOF { //Client 关闭了会话 msg.Mid = msgcmd.MCMD_C2M_CLIENTEXIT println("Client 关闭了会话") isRun = false } println("Msg Server Error: 接收数据 失败. ", err.Error()) logFile.Printf("Msg Server Error: 接收数据 失败. ", err.Error()) } user.MsgChan <- msg } }() FORLOOP: for { timer := time.NewTimer(this.cfg.Expire * time.Second) var msg *msgcmd.Cmd select { case msg = <-user.MsgChan: case <-timer.C: //接收客户端消息超时,客户端未做任何操作,同时没有心跳包发送过来,判定用户已经离线 msg = msgcmd.NewCmd(msgcmd.MCMD_C2M_CLIENTEXIT) println("客户端操作超时") } timer.Stop() switch msg.Mid { case msgcmd.MCMD_C2M_REGISTER: this.DoRegister(msg, user) case msgcmd.MCMD_C2M_LOGIN: this.DoLogin(msg, user) case msgcmd.MCMD_C2M_HEARTBEAT: this.DoHeartBeat(msg, user) case msgcmd.MCMD_C2M_REQUEST_ONLINEUSERS: this.DoRequestOnlineUsers(msg, user) case msgcmd.MCMD_C2M_CLIENTEXIT: this.DoClientExit(user) break FORLOOP default: if msg != nil { println("好像接收到了什么...") } } } println("用户Go程退出") }