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
|
func main() {
// 配置ssl,"*.heliu.site"在实际开发中从浏览器中取获取,证书路径使用绝对路径
creds, _ := credentials.NewClientTLSFromFile(
"/root/workspace/learn-grpc/key/test.pem",
"*.heliu.site",
)
var opts []grpc.DialOption
// 不带TLS这里是grpc.WithTransportCredentials(insecure.NewCredentials())
opts = append(opts, grpc.WithTransportCredentials(creds))
opts = append(opts, grpc.WithPerRPCCredentials(&ClientTokenAuth{}))
// 添加客户端拦截器
opts = append(opts, grpc.WithUnaryInterceptor(interceptor.UnaryClientInterceptor()))
// 添加流拦截器
opts = append(opts, grpc.WithStreamInterceptor(interceptor.StreamClientInterceptor()))
// 连接server端,使用ssl加密通信
conn, err := grpc.NewClient("127.0.0.1:9090", opts...)
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
// 建立连接
client := pb.NewSayHelloClient(conn)
fmt.Printf("now-Time: %s\n", time.Now().Format(time.DateTime))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var header metadata.MD
var tr metadata.MD
var opts1 []grpc.CallOption = []grpc.CallOption{
grpc.WaitForReady(false),
grpc.Header(&header),
grpc.Trailer(&tr),
}
// 执行rpc调用(这个方法在服务器端来实现并返回结构)
resp, err := client.SayHello(ctx, &pb.HelloRequest{RequestName: "gh", Age: 12}, opts1...)
if err != nil {
fmt.Printf("%v\n", err)
return
}
fmt.Printf("Response-Header: %v\n", header)
fmt.Println(resp.GetResponseMsg())
fmt.Printf("Response-Trailer: %v\n", tr)
// 客户端调用Channel方法,获取返回的流对象
stream, err := client.Channel(context.Background())
if err != nil {
log.Fatalf("error creating stream: %v", err)
}
// 在客户端将发送和接收放到两个独立的 goroutine
// 向服务器发送数据:
go func() {
for {
req := &pb.Request{
Value: "张三",
}
if err := stream.Send(req); err != nil {
log.Fatalf("error sending message: %v", err)
return
}
time.Sleep(time.Second)
}
}()
// 然后再循环中接收服务端返回的数据
for {
reply, err := stream.Recv()
if err != nil {
if err == io.EOF {
break
}
log.Fatalf("error receiving message: %v", err)
return
}
fmt.Printf("Received: %s\n", reply.GetValue())
}
}
|