//更新回调函数定义 func process(r *robot.Robot) { if r.UserData == nil { //用户数据为空 elog.LogInfoln(" user data ", r.UserData) r.UserData = &User{ //创建用户 name: strconv.Itoa(int(r.GetId())), pwd: "123", state: kStateIdle, //初始状态为空闲 r: r, } user := r.UserData.(*User) user.RegisterCb() //注册状态回调 } //elog.LogInfoln( " user data ", r.UserData ) user := r.UserData.(*User) user.stateCbs[user.state](user) //根据用户状态执行回调 }
//启动机器人 func (r *Robot) Run() { elog.LogDebug(" robot %d begin run ", r.id) var err error r.addr, err = net.ResolveTCPAddr("tcp", gateAddr) //解析服务器地址 if err != nil { elog.LogErrorln(gateAddr, ":resolve tcp addr fail, please try: 127.0.0.1:3563, fail: ", err) return } r.tcpConn, err = net.DialTCP("tcp", nil, r.addr) //连接服务器 if err != nil { elog.LogErrorln("connect server fail , because :", err) return } elog.LogInfoln(" connect server sucess :", r.id, r.tcpConn.RemoteAddr().String()) r.state = kRobotActive //设置机器人状态 r.waitGroup.Run(r.SendLoop) //启动发送循环 r.waitGroup.Run(r.RecvLoop) //启动接收循环 r.ticker = time.NewTicker(defDur) //启动机器人时钟 defer r.Close() //延迟关闭机器人 for { select { case <-r.closeCh: //关闭通道 elog.LogDebugln("update loop begin stop ") return case <-r.ticker.C: //时钟到时 //逻辑处理 r.update() //elog.LogInfoln("robot :", r.id, "heart :", t) default: } } }