-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
79 lines (68 loc) · 1.28 KB
/
client.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
package heartbeat
import (
"context"
"io"
"log"
"time"
"github.com/franklange/go-heartbeat/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type Client struct {
id string
quit chan bool
conn *grpc.ClientConn
client proto.HeartbeatClient
stream proto.Heartbeat_ConnectClient
}
type ClientConfig struct {
Id string
Addr string
Interval time.Duration
}
func NewClient(config *ClientConfig) *Client {
conn, err := grpc.NewClient(config.Addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("NewClient: %v", err)
}
c := &Client{
id: config.Id,
quit: make(chan bool, 1),
conn: conn,
client: proto.NewHeartbeatClient(conn),
}
go c.run(config.Interval)
return c
}
func (c *Client) Stop() {
c.quit <- true
if c.stream != nil {
c.stream.CloseAndRecv()
}
c.conn.Close()
}
func (c *Client) run(d time.Duration) {
c.beat()
t := time.NewTicker(d)
for {
select {
case <-c.quit:
return
case <-t.C:
c.beat()
}
}
}
func (c *Client) beat() {
if c.stream == nil {
stream, err := c.client.Connect(context.Background())
if err != nil {
return
}
c.stream = stream
}
err := c.stream.Send(&proto.Beat{ClientId: c.id})
if err == io.EOF {
c.stream = nil
}
}