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.
protolab/bin/bin.go

46 lines
956 B

package bin
import (
"bytes"
"fmt"
"io"
"net"
"google.golang.org/protobuf/proto"
)
func WriteMessage(conn net.Conn, m proto.Message) error {
data, err := proto.Marshal(m)
if err != nil {
return fmt.Errorf("proto.Marshal: %w", err)
}
var (
length = len(data)
w = bytes.NewBuffer(nil)
)
w.Write([]byte{
byte(length),
byte(length >> 8),
})
w.Write(data)
if _, err := conn.Write(w.Bytes()); err != nil {
return fmt.Errorf("conn.Write: %w", err)
}
return nil
}
func ReadMessage(conn net.Conn, m proto.Message) error {
buf := make([]byte, 2)
if _, err := io.ReadFull(conn, buf); err != nil {
return fmt.Errorf("io.ReadFull: %w", err)
}
length := int(buf[0]) | (int(buf[1]) << 8)
buf = make([]byte, length)
if _, err := io.ReadFull(conn, buf); err != nil {
return fmt.Errorf("io.ReadFull: %w", err)
}
if err := proto.Unmarshal(buf, m); err != nil {
return fmt.Errorf("proto.Unmarshal: %w", err)
}
return nil
}