-
Notifications
You must be signed in to change notification settings - Fork 10
/
packet.go
78 lines (64 loc) · 1.56 KB
/
packet.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
71
72
73
74
75
76
77
78
package stream_packet
import (
"encoding/binary"
"io"
"sync"
protobuf_go_lite "github.com/aperturerobotics/protobuf-go-lite"
"github.com/pkg/errors"
)
// Session wraps a stream in a session.
type Session struct {
io.ReadWriteCloser
sendMtx sync.Mutex
readMtx sync.Mutex
maxMessageSize uint32
}
// NewSession builds a new session.
func NewSession(
stream io.ReadWriteCloser,
maxMessageSize uint32,
) *Session {
return &Session{
ReadWriteCloser: stream,
maxMessageSize: maxMessageSize,
}
}
// SendMsg tries to send a message on the wire.
func (s *Session) SendMsg(msg protobuf_go_lite.Message) error {
data, err := msg.MarshalVT()
if err != nil {
return err
}
pktBuf := make([]byte, len(data)+4)
copy(pktBuf[4:], data)
msgLen := uint32(len(data))
binary.LittleEndian.PutUint32(pktBuf, msgLen)
s.sendMtx.Lock()
defer s.sendMtx.Unlock()
if _, err := s.ReadWriteCloser.Write(pktBuf); err != nil {
return err
}
return nil
}
// RecvMsg tries to receive a message on the wire.
func (s *Session) RecvMsg(msg protobuf_go_lite.Message) error {
data := make([]byte, 4)
s.readMtx.Lock()
defer s.readMtx.Unlock()
if _, err := io.ReadFull(s.ReadWriteCloser, data); err != nil {
return err
}
messageLen := binary.LittleEndian.Uint32(data)
if messageLen > 0 {
if messageLen > s.maxMessageSize {
return errors.Errorf("invalid message len: %d", messageLen)
}
data = make([]byte, messageLen)
if _, err := io.ReadFull(s.ReadWriteCloser, data); err != nil {
return err
}
return msg.UnmarshalVT(data)
}
msg.Reset()
return nil
}