Example #1
0
//读取
func (self *Session) ReadPacket() {

	//缓存本次包的数据
	for !self.isClose {

		func() {
			defer func() {
				if err := recover(); nil != err {
					log.Error("Session|ReadPacket|%s|recover|FAIL|%s", self.remoteAddr, err)
				}
			}()
			buffer, err := self.decoder.Read(self.br)
			if nil != err {
				self.Close()
				log.Error("Session|ReadPacket|%s|FAIL|CLOSE SESSION|%s", self.remoteAddr, err)
				return
			} else {
				// log.Debug("Session|ReadPacket|%s|SUCC|%d", self.remoteAddr, buffer.Len())
			}

			p, err := packet.UnmarshalTLV(buffer)
			if nil != err {
				self.Close()
				log.Error("Session|ReadPacket|MarshalPacket|%s|FAIL|CLOSE SESSION|%s", self.remoteAddr, err)
				return
			}

			//写入缓冲
			self.ReadChannel <- p
			//重置buffer
			if nil != self.rc.FlowStat {
				self.rc.FlowStat.ReadFlow.Incr(1)
				self.rc.FlowStat.ReadBytesFlow.Incr(int32(buffer.Len()))
			}
		}()
	}
}
Example #2
0
//读取
func (self *Session) ReadPacket() {

	defer func() {
		if err := recover(); nil != err {
			log.Error("Session|ReadPacket|%s|recover|FAIL|%s\n", self.remoteAddr, err)
		}
	}()

	//缓存本次包的数据
	buff := make([]byte, 0, self.rc.ReadBufferSize)
	var tlv *packet.Packet
	for !self.isClose {
		line, err := self.br.ReadSlice(packet.CMD_CRLF[1])
		//如果没有达到请求头的最小长度则继续读取
		if nil != err {
			buff = buff[:0]
			// buff.Reset()
			//链接是关闭的
			if err == io.EOF ||
				err == syscall.EPIPE ||
				err == syscall.ECONNRESET {
				self.Close()
				log.Error("Session|ReadPacket|%s|\\r|FAIL|CLOSE SESSION|%s\n", self.remoteAddr, err)
			}
			continue
		}

		l := len(buff) + len(line)
		//如果是\n那么就是一个完整的包
		if l >= packet.MAX_PACKET_BYTES {
			log.Error("Session|ReadPacket|%s|WRITE|TOO LARGE|CLOSE SESSION|%s\n", self.remoteAddr, err)
			self.Close()
			return
		} else {
			buff = append(buff, line...)
		}

		//complete packet
		if buff[len(buff)-2] == packet.CMD_CRLF[0] {

			//还没有tlv则umarshaltlv
			if nil == tlv && l >= packet.PACKET_HEAD_LEN {
				packet, err := packet.UnmarshalTLV(buff)
				if nil != err || nil == packet {
					log.Error("Session|ReadPacket|UnmarshalTLV|FAIL|%s|%d|%s\n", err, len(buff), buff)
					buff = buff[:0]
					continue
				}
				tlv = packet
			} else if nil == tlv && l < packet.PACKET_HEAD_LEN {
				//不够包头则再次读取
				continue
			}

			if nil != tlv {
				//如果tlv不为空则直接拼接数据
				full := tlv.AppendData(buff)
				if !full {
					continue
				}
			}

			p := tlv
			tlv = nil
			//写入缓冲
			self.ReadChannel <- p
			//重置buffer
			if nil != self.rc.FlowStat {
				self.rc.FlowStat.ReadFlow.Incr(1)
			}

			buff = buff[:0]
		}
	}
}