-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpacket.go
More file actions
53 lines (41 loc) · 1.06 KB
/
packet.go
File metadata and controls
53 lines (41 loc) · 1.06 KB
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
package dnet
import (
"bytes"
"errors"
"github.com/golang/protobuf/proto"
"github.com/cima-go/dnet/lan"
"github.com/cima-go/dnet/spec"
)
var magic = " DNETv1"
// CType is command type
type CType uint8
const (
UNKNOWN CType = iota // default
KNOCKING // Client knocking
IDENTIFY // Server identify
REQUEST // RPC Request
REPLY // RPC Response
)
func knockRequest() []byte {
return encodePacket(KNOCKING, nil)
}
func knockResponse(peer lan.Discovered, identify *spec.Identify) {
if bs, err := proto.Marshal(identify); err == nil {
peer.Reply(encodePacket(IDENTIFY, bs))
}
}
func encodePacket(cmd CType, data []byte) []byte {
buf := bytes.NewBufferString(magic)
buf.WriteByte(byte(cmd))
buf.Write(data)
return buf.Bytes()
}
func decodePacket(payload []byte) (cmd CType, data []byte, err error) {
if !bytes.HasPrefix(payload, []byte(magic)) || len(payload) <= len(magic) {
err = errors.New("invalid packet")
return
}
cmd = CType(payload[len(magic)])
data = payload[len(magic)+1:]
return
}