-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathserver.go
70 lines (64 loc) · 1.41 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
package main
import (
"bytes"
"fmt"
"time"
"github.com/golang/protobuf/jsonpb"
log "github.com/sirupsen/logrus"
"github.com/tmc/grpc-websocket-proxy/examples/cmd/wsechoserver/echoserver"
)
type Server struct{}
func (s *Server) Stream(_ *echoserver.Empty, stream echoserver.EchoService_StreamServer) error {
start := time.Now()
for i := 0; i < 5; i++ {
time.Sleep(time.Second)
if err := stream.Send(&echoserver.EchoResponse{
Message: "hello there!" + fmt.Sprint(time.Now().Sub(start)),
}); err != nil {
return err
}
}
return nil
}
func (s *Server) Echo(srv echoserver.EchoService_EchoServer) error {
for {
req, err := srv.Recv()
if err != nil {
return err
}
if err := srv.Send(&echoserver.EchoResponse{
Message: req.Message + "!",
}); err != nil {
return err
}
}
}
func (s *Server) Heartbeats(srv echoserver.EchoService_HeartbeatsServer) error {
go func() {
for {
_, err := srv.Recv()
if err != nil {
log.Println("Recv() err:", err)
return
}
log.Println("got hb from client")
}
}()
t := time.NewTicker(time.Second * 1)
for {
log.Println("sending hb")
hb := &echoserver.Heartbeat{
Status: echoserver.Heartbeat_OK,
}
b := new(bytes.Buffer)
if err := (&jsonpb.Marshaler{}).Marshal(b, hb); err != nil {
log.Println("marshal err:", err)
}
log.Println(string(b.Bytes()))
if err := srv.Send(hb); err != nil {
return err
}
<-t.C
}
return nil
}