-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
93 lines (82 loc) · 1.45 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package metad
import (
"context"
"sync"
"time"
"github.com/tddhit/tools/log"
metadpb "github.com/tddhit/xsearch/metad/pb"
)
type client struct {
addr string
namespace string
readC chan *metadpb.RegisterClientReq
writeC chan *metadpb.RegisterClientRsp
}
func newClient(addr, namespace string) *client {
return &client{
addr: addr,
namespace: namespace,
readC: make(chan *metadpb.RegisterClientReq, 100),
writeC: make(chan *metadpb.RegisterClientRsp, 100),
}
}
func (c *client) readLoop(ctx context.Context) {
timer := time.NewTimer(3 * time.Second)
for {
select {
case <-c.readC:
timer.Reset(3 * time.Second)
case <-timer.C:
goto exit
case <-ctx.Done():
goto exit
}
}
exit:
timer.Stop()
c.close()
}
func (c *client) writeLoop(ctx context.Context,
stream metadpb.Metad_RegisterClientServer) {
for {
select {
case rsp, ok := <-c.writeC:
if !ok {
goto exit
}
if rsp != nil {
if err := stream.Send(rsp); err != nil {
log.Error(err)
}
}
case <-ctx.Done():
goto exit
}
}
exit:
}
func (c *client) ioLoop(
ctx context.Context,
stream metadpb.Metad_RegisterClientServer) {
var wg sync.WaitGroup
wg.Add(2)
go func() {
c.readLoop(ctx)
wg.Done()
}()
go func() {
c.writeLoop(ctx, stream)
wg.Done()
}()
wg.Wait()
}
func (c *client) close() {
if c.readC != nil {
close(c.readC)
c.readC = nil
}
if c.writeC != nil {
close(c.writeC)
c.writeC = nil
}
}