-
Notifications
You must be signed in to change notification settings - Fork 18
/
stream.go
91 lines (73 loc) · 1.92 KB
/
stream.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
package cleisthenes
import (
"context"
"github.com/DE-labtory/cleisthenes/pb"
"google.golang.org/grpc"
)
type Stream interface {
Send(message *pb.Message) error
Recv() (*pb.Message, error)
}
type StreamWrapper interface {
Stream
Close()
GetStream() Stream
}
// client side stream wrapper
type CStreamWrapper struct {
conn *grpc.ClientConn
client pb.StreamServiceClient
clientStream pb.StreamService_MessageStreamClient
cancel context.CancelFunc
}
func NewClientStreamWrapper(conn *grpc.ClientConn) (StreamWrapper, error) {
ctx, cf := context.WithCancel(context.Background())
streamserviceClient := pb.NewStreamServiceClient(conn)
clientStream, err := streamserviceClient.MessageStream(ctx)
if err != nil {
return nil, err
}
return &CStreamWrapper{
conn: conn,
client: streamserviceClient,
clientStream: clientStream,
cancel: cf,
}, nil
}
func (csw *CStreamWrapper) Send(message *pb.Message) error {
return csw.clientStream.Send(message)
}
func (csw *CStreamWrapper) Recv() (*pb.Message, error) {
return csw.clientStream.Recv()
}
func (csw *CStreamWrapper) Close() {
csw.conn.Close()
csw.clientStream.CloseSend()
csw.cancel()
}
func (csw *CStreamWrapper) GetStream() Stream {
return csw.clientStream
}
// server side stream wrapper
type SStreamWrapper struct {
ServerStream pb.StreamService_MessageStreamServer
cancel context.CancelFunc
}
func NewServerStreamWrapper(serverStream pb.StreamService_MessageStreamServer, cancel context.CancelFunc) StreamWrapper {
return &SStreamWrapper{
cancel: cancel,
ServerStream: serverStream,
}
}
func (ssw *SStreamWrapper) Send(message *pb.Message) error {
return ssw.ServerStream.Send(message)
}
func (ssw *SStreamWrapper) Recv() (*pb.Message, error) {
return ssw.ServerStream.Recv()
}
func (ssw *SStreamWrapper) Close() {
ssw.cancel()
}
func (ssw *SStreamWrapper) GetStream() Stream {
return ssw.ServerStream
}