first commit
This commit is contained in:
46
bin/bin.go
Normal file
46
bin/bin.go
Normal file
@@ -0,0 +1,46 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user