-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
77 lines (63 loc) · 1.19 KB
/
server.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
package heartbeat
import (
"fmt"
"log"
"net"
"github.com/franklange/go-heartbeat/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/peer"
)
type Peer struct {
Id string
Addr string
}
type Server struct {
proto.UnimplementedHeartbeatServer
grpcServer *grpc.Server
Dead chan Peer
Alive chan Peer
}
func NewHeartbeatServer(port string) *Server {
s := &Server{
Dead: make(chan Peer, 100),
Alive: make(chan Peer, 100),
grpcServer: grpc.NewServer(),
}
lis, err := net.Listen("tcp", fmt.Sprint("localhost:", port))
if err != nil {
log.Fatalf("listen: %v", err)
}
proto.RegisterHeartbeatServer(s.grpcServer, s)
go func() {
if err := s.grpcServer.Serve(lis); err != nil {
log.Fatalf("serve: %v", err)
}
}()
return s
}
func (s *Server) Stop() {
s.grpcServer.Stop()
}
func (s *Server) Connect(stream proto.Heartbeat_ConnectServer) error {
var p Peer
for {
beat, err := stream.Recv()
if err != nil {
if p.Id != "" {
s.Dead <- p
}
return err
}
if p.Id != "" {
continue
}
p.Id = beat.ClientId
pp, ok := peer.FromContext(stream.Context())
if !ok {
p.Addr = "unknown"
} else {
p.Addr = pp.Addr.String()
}
s.Alive <- p
}
}