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) SendLoop() {
	defer r.Close()
	elog.LogDebug(" robot %d  send  loop run  ", r.id)
	for {
		select {
		case msg := <-r.sendCh: //从发送通道取出待发送消息
			elog.LogInfo("  encode  msg :%d ", msg.id)
			binary.Write(r.sendBuf, binary.LittleEndian, msg.id)   //写ID
			binary.Write(r.sendBuf, binary.LittleEndian, msg.Data) //写数据
			byte := r.sendBuf.Bytes()
			n, err := r.tcpConn.Write(byte)
			if err != nil {
				elog.LogSysln(" conn ", r.id, " write data fail :", err)
				return
			}

			elog.LogInfo(" write  msg :%d ", n, hex.Dump(r.sendBuf.Bytes()))
		case <-r.closeCh: //机器人关闭信号
			elog.LogDebug(" send loop begin close ")
			return
		}
	}

	elog.LogDebug("send loop close  ")
}