-
Notifications
You must be signed in to change notification settings - Fork 5
/
protocol.go
102 lines (84 loc) · 2.27 KB
/
protocol.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package heartbeat
import (
"encoding/gob"
"fmt"
"time"
"github.com/antongulenko/RTP/protocols"
)
var (
Protocol *heartbeatProtocol
MiniProtocol = protocols.NewMiniProtocol(Protocol)
)
// ======================= Packets =======================
const (
codeHeartbeat = protocols.Code(iota + 6)
codeConfigureHeartbeat
)
type HeartbeatPacket struct {
Token int64
Source string
TimeSent time.Time
Seq uint64
}
type ConfigureHeartbeatPacket struct {
Token int64
TargetServer string
Timeout time.Duration
}
// ======================= Protocol =======================
type heartbeatProtocol struct {
}
func (*heartbeatProtocol) Name() string {
return "Heartbeat"
}
func (proto *heartbeatProtocol) Decoders() protocols.DecoderMap {
return protocols.DecoderMap{
codeHeartbeat: proto.decodeHeartbeat,
codeConfigureHeartbeat: proto.decodeConfigureHeartbeat,
}
}
func (proto *heartbeatProtocol) decodeHeartbeat(decoder *gob.Decoder) (interface{}, error) {
var val HeartbeatPacket
err := decoder.Decode(&val)
if err != nil {
return nil, fmt.Errorf("Error decoding Heartbeat value: %v", err)
}
return &val, nil
}
func (proto *heartbeatProtocol) decodeConfigureHeartbeat(decoder *gob.Decoder) (interface{}, error) {
var val ConfigureHeartbeatPacket
err := decoder.Decode(&val)
if err != nil {
return nil, fmt.Errorf("Error decoding ConfigureHeartbeat value: %v", err)
}
return &val, nil
}
// ======================= Client =======================
type Client struct {
protocols.Client
}
func NewClient(client protocols.Client) (*Client, error) {
if err := client.Protocol().CheckIncludesFragment(Protocol.Name()); err != nil {
return nil, err
}
return &Client{client}, nil
}
func NewClientFor(server_addr string) (*Client, error) {
client, err := protocols.NewMiniClientFor(server_addr, Protocol)
if err != nil {
return nil, err
}
return &Client{client}, nil
}
func (client *Client) ConfigureHeartbeat(receiver *protocols.Server, token int64, timeout time.Duration) error {
packet := ConfigureHeartbeatPacket{
Token: token,
TargetServer: receiver.LocalAddr().String(),
Timeout: timeout,
}
reply, err := client.SendRequest(codeConfigureHeartbeat, packet)
if err != nil {
return err
}
return client.CheckReply(reply)
}