Example #1
0
//接收循环
func (r *Robot) RecvLoop() {
	defer r.Close()
	elog.LogDebug(" robot %d  read loop run  ", r.id)
	buf := make([]byte, 1024*1024)
	for {
		select {
		case <-r.closeCh: //机器人关闭信号
			elog.LogSysln("read loop begin stop ")
			return
		default:
		}

		r.tcpConn.SetDeadline(time.Now().Add(1e9))
		n, err := r.tcpConn.Read(buf)
		if err != nil {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				continue
			}
			elog.LogErrorln(" read data error ", err)
			return
		}
		elog.LogSys(" ********* read data : %d ", n)
		r.recvBuf.Write(buf[0:n])

		var msg Message
		binary.Read(r.recvBuf, binary.LittleEndian, msg.id)
		msg.Data = make([]byte, r.recvBuf.Len())
		r.recvBuf.Read(msg.Data)

		r.recvCh <- msg
	}

}
Example #2
0
//启动机器人
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:
		}
	}
}