golang 处理TCP粘包问题

func Encode(data []byte) []byte {
	buf := bytes.NewBuffer(nil)
	binary.Write(buf, binary.BigEndian, uint32(len(data)))
	binary.Write(buf, binary.BigEndian, data)
	return buf.Bytes()
}

func Decode(data []byte) ([]byte, error) {
	reader := bufio.NewReader(bytes.NewBuffer(data))
	peek, err := reader.Peek(4)
	if err != nil {
		return nil, err
	}
	buffer := bytes.NewBuffer(peek)
	var length uint32
	err = binary.Read(buffer, binary.LittleEndian, &length)
	if err != nil {
		return nil, err
	}
	if uint32(reader.Buffered()) < length+4 {
		return nil, errors.New("长度不足")
	}
	data = make([]byte, length+4)
	_, err = reader.Read(data)
	if err != nil {
		return nil, err
	}
	return data[4:], nil
}

  

posted @ 2020-08-08 23:42  闲云-野鹤  阅读(269)  评论(0编辑  收藏  举报