-
Notifications
You must be signed in to change notification settings - Fork 1
/
stream_test.go
91 lines (80 loc) · 1.81 KB
/
stream_test.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
// Copyright (c) 2019 Meng Huang (mhboy@outlook.com)
// This package is licensed under a MIT license that can be found in the LICENSE file.
package rpc
import (
"sync"
"testing"
"time"
)
func TestStream(t *testing.T) {
network := "tcp"
addr := ":9999"
codec := "json"
server := NewServer()
server.Register(new(mockStreamArith))
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
server.Listen(network, addr, codec)
}()
time.Sleep(time.Millisecond * 10)
conn, err := Dial(network, addr, codec)
if err != nil {
panic(err)
}
stream, err := conn.NewStream("mockStreamArith.StreamMultiply")
if err != nil {
t.Error(err)
}
for i := 0; i < 3; i++ {
req := &mockStreamArithRequest{A: int32(i), B: int32(i + 1)}
var res mockStreamArithResponse
if err := stream.WriteMessage(req); err != nil {
t.Error(err)
}
buf := make([]byte, 64)
if err := stream.ReadMessage(buf, &res); err != nil {
t.Error(err)
}
}
stream.Close()
conn.Close()
server.Close()
wg.Wait()
}
type mockStreamArithRequest struct {
A int32
B int32
}
type mockStreamArithResponse struct {
Pro int32 //product
}
type mockStreamArith struct{}
func (a *mockStreamArith) StreamMultiply(stream *mockStream) error {
for {
var req = &mockStreamArithRequest{}
if err := stream.Read(nil, req); err != nil {
return err
}
res := mockStreamArithResponse{}
res.Pro = req.A * req.B
if err := stream.Write(&res); err != nil {
println(err.Error())
return err
}
}
}
type mockStream struct {
stream Stream
}
func (s *mockStream) Connect(stream Stream) error {
s.stream = stream
return nil
}
func (s *mockStream) Read(buf []byte, req *mockStreamArithRequest) error {
return s.stream.ReadMessage(buf, req)
}
func (s *mockStream) Write(res *mockStreamArithResponse) error {
return s.stream.WriteMessage(res)
}