You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
2.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package netProgram
import (
"bytes"
"encoding/binary"
"errors"
"io"
"log"
)
// 定义编码器(发送端)
type Encoder struct {
// 编码结束后,写入的目标
w io.Writer
}
// 创建编码器函数
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{
w: w,
}
}
// 编码将编码的结果写入到w io.Writer
// binary(int32(13))[]byte("package data.")
func (enc *Encoder) Encode(message string) error {
// 1获取message的长度
l := int32(len(message))
// 构建一个数据包缓存
buf := new(bytes.Buffer)
// 2在数据包中写入长度
// 需要二进制的写入操作需要将数据以bit的形式写入
if err := binary.Write(buf, binary.LittleEndian, l); err != nil {
return err
}
// 3将数据主体Body写入
//if err := binary.Write(buf, binary.LittleEndian, []byte(message)); err != nil {
// return err
//}
if _, err := buf.Write([]byte(message)); err != nil {
return err
}
// 4利用io.Writer发送数据
if n, err := enc.w.Write(buf.Bytes()); err != nil {
log.Println(n, err)
return err
}
return nil
}
// 定义解码器(接收端)
// 解码器
type Decoder struct {
// Reader
r io.Reader
}
// 创建Decoder
func NewDecoder(r io.Reader) *Decoder {
return &Decoder{
r: r,
}
}
// 从Reader中读取内容解码
// binary(int32(13))[]byte("package data.")
func (dec *Decoder) Decode(message *string) error {
// 1读取前4个字节读取header
header := make([]byte, 4)
hn, err := dec.r.Read(header)
if err != nil {
return err
}
if hn != 4 {
return errors.New("header is not enough")
}
// 2将前4个字节转换为int32类型确定了body的长度
var l int32
headerBuf := bytes.NewBuffer(header)
if err := binary.Read(headerBuf, binary.LittleEndian, &l); err != nil {
return err
}
// 3读取body
body := make([]byte, l)
bn, err := dec.r.Read(body)
if err != nil {
return err
}
if bn != int(l) {
return errors.New("body is not enough")
}
// 4设置message
*message = string(body)
return nil
}