Go语言 序列化反序列化二进制包

包的定义格式是长度,校验码和json内容

package main

import (
	"bytes"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"hash/crc32"
	"io"
	"net"
	"os"
)

type Register struct {
	ACTION int32
	SID    int32
}

type Packet struct {
	length uint32
	crc32  uint32
	info   string
}

func (p Packet) Encode() []byte {
	buf2 := new(bytes.Buffer)
	var length int = len([]byte(p.info))
	err := binary.Write(buf2, binary.LittleEndian, (int32)(length))
	checkError(err)

	err = binary.Write(buf2, binary.LittleEndian, []byte(p.info))
	checkError(err)

	buf := new(bytes.Buffer)
	p.length = uint32(buf2.Len() + 8)
	err = binary.Write(buf, binary.LittleEndian, p.length)
	checkError(err)

	p.crc32 = crc32.ChecksumIEEE(buf2.Bytes())
	err = binary.Write(buf, binary.LittleEndian, p.crc32)
	checkError(err)

	err = binary.Write(buf, binary.LittleEndian, buf2.Bytes())
	checkError(err)
	return buf.Bytes()
}

func (p *Packet) Decode(buff []byte) {
	buf := bytes.NewBuffer(buff)
	err := binary.Read(buf, binary.LittleEndian, &(p.length))
	checkError(err)
	fmt.Println(p.length)

	err = binary.Read(buf, binary.LittleEndian, &(p.crc32))
	checkError(err)

	buf2 := bytes.NewBuffer(buff[8:])
	crc := crc32.ChecksumIEEE(buf2.Bytes())
	if crc != p.crc32 {
		fmt.Errorf(" crc not check")
	}

	p.info = (string)(buf2.Bytes())
	fmt.Printf("%s", p.info)
}

func main() {
	m := Register{20004, 6}
	b, err := json.Marshal(m)
	checkError(err)

	var packet Packet
	packet.info = string(b)
	buf := packet.Encode()
	fmt.Println(len(buf))

	var msg Packet
	msg.Decode(buf)

	os.Exit(0)
}

func checkError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
		os.Exit(1)
	}
}


你可能感兴趣的:(go语言)