-
Notifications
You must be signed in to change notification settings - Fork 0
/
protoconn.go
70 lines (59 loc) · 1.69 KB
/
protoconn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"encoding/binary"
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
"io"
"net"
)
// read the data length from message header
// The header is a 4 byte big endian uint32
func readDataLength(conn net.Conn) (length uint32, err error) {
header := make([]byte, 4)
if _, err := io.ReadFull(conn, header); err != nil {
return 0, errors.Wrap(err, "unable to read data length")
}
length = binary.BigEndian.Uint32(header)
return
}
// write the data length to the message header
// The header is a 4 byte big endian uint32
func writeDataLength(conn net.Conn, dataLength int) error {
header := make([]byte, 4)
binary.BigEndian.PutUint32(header, uint32(dataLength))
n, err := conn.Write(header)
if err != nil {
return errors.Wrap(err, "unable to write data length")
}
if n != 4 {
return errors.New("invalid size written")
}
return nil
}
func SendMessage(conn net.Conn, message proto.Message) error {
data, err := proto.Marshal(message)
if err != nil {
return errors.Wrap(err, "marshaling error")
}
if err = writeDataLength(conn, len(data)); err != nil {
return errors.Wrap(err, "unable to write data length")
}
if _, err = conn.Write(data); err != nil {
return errors.Wrap(err, "unable to write data")
}
return nil
}
func ReceiveMessage(conn net.Conn, message proto.Message) error {
dataLength, err := readDataLength(conn)
if err != nil {
return errors.Wrap(err, "unable to read data length")
}
data := make([]byte, dataLength)
if _, err = io.ReadFull(conn, data); err != nil {
return errors.Wrap(err, "unable to read data")
}
if err = proto.Unmarshal(data, message); err != nil {
return errors.Wrap(err, "unable to unmarshal data")
}
return nil
}