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
}

  

原文地址:https://www.cnblogs.com/tl542475736/p/13461081.html