代码拉取完成,页面将自动刷新
package main
import (
"bytes"
"encoding/binary"
"fmt"
"io"
)
type pack struct {
Version []byte
Length int64
Data []byte
}
func main() {
var err error
Pack := pack{
Version: []byte("v1"),
Length: int64(4),
Data: []byte("data"),
}
writer := new(bytes.Buffer)
err = Pack.Pack(writer)
if err != nil {
fmt.Println("打包错误,err: ", err)
return
}
Result := pack{}
err = Result.Unpack(writer)
if err != nil {
fmt.Println("解包错误,err: ", err)
return
}
Result.Data = make([]byte, Result.Length)
err = binary.Read(writer, binary.BigEndian, &Result.Data)
Result.String()
fmt.Println()
}
func (p *pack) Pack(buf io.Writer) error {
var err error
err = binary.Write(buf, binary.BigEndian, &p.Version)
err = binary.Write(buf, binary.BigEndian, &p.Length)
err = binary.Write(buf, binary.BigEndian, &p.Data)
return err
}
func (p *pack) Unpack(r io.Reader) error {
var err error
p.Version = make([]byte, 2)
err = binary.Read(r, binary.BigEndian, &p.Version)
err = binary.Read(r, binary.BigEndian, &p.Length)
//p.Data = make([]byte, p.Length)
//err = binary.Read(r, binary.BigEndian, &p.Data)
return err
}
func (p *pack) String() {
fmt.Printf("Version: %s, Length: %d, Data: %s\n",
p.Version,
p.Length,
string(p.Data),
)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。