OSDN Git Service

new repo
[bytom/vapor.git] / vendor / google.golang.org / grpc / examples / route_guide / client / client.go
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18
19 // Package main implements a simple gRPC client that demonstrates how to use gRPC-Go libraries
20 // to perform unary, client streaming, server streaming and full duplex RPCs.
21 //
22 // It interacts with the route guide service whose definition can be found in routeguide/route_guide.proto.
23 package main
24
25 import (
26         "flag"
27         "io"
28         "log"
29         "math/rand"
30         "time"
31
32         "golang.org/x/net/context"
33         "google.golang.org/grpc"
34         "google.golang.org/grpc/credentials"
35         pb "google.golang.org/grpc/examples/route_guide/routeguide"
36         "google.golang.org/grpc/testdata"
37 )
38
39 var (
40         tls                = flag.Bool("tls", false, "Connection uses TLS if true, else plain TCP")
41         caFile             = flag.String("ca_file", "", "The file containning the CA root cert file")
42         serverAddr         = flag.String("server_addr", "127.0.0.1:10000", "The server address in the format of host:port")
43         serverHostOverride = flag.String("server_host_override", "x.test.youtube.com", "The server name use to verify the hostname returned by TLS handshake")
44 )
45
46 // printFeature gets the feature for the given point.
47 func printFeature(client pb.RouteGuideClient, point *pb.Point) {
48         log.Printf("Getting feature for point (%d, %d)", point.Latitude, point.Longitude)
49         feature, err := client.GetFeature(context.Background(), point)
50         if err != nil {
51                 log.Fatalf("%v.GetFeatures(_) = _, %v: ", client, err)
52         }
53         log.Println(feature)
54 }
55
56 // printFeatures lists all the features within the given bounding Rectangle.
57 func printFeatures(client pb.RouteGuideClient, rect *pb.Rectangle) {
58         log.Printf("Looking for features within %v", rect)
59         stream, err := client.ListFeatures(context.Background(), rect)
60         if err != nil {
61                 log.Fatalf("%v.ListFeatures(_) = _, %v", client, err)
62         }
63         for {
64                 feature, err := stream.Recv()
65                 if err == io.EOF {
66                         break
67                 }
68                 if err != nil {
69                         log.Fatalf("%v.ListFeatures(_) = _, %v", client, err)
70                 }
71                 log.Println(feature)
72         }
73 }
74
75 // runRecordRoute sends a sequence of points to server and expects to get a RouteSummary from server.
76 func runRecordRoute(client pb.RouteGuideClient) {
77         // Create a random number of random points
78         r := rand.New(rand.NewSource(time.Now().UnixNano()))
79         pointCount := int(r.Int31n(100)) + 2 // Traverse at least two points
80         var points []*pb.Point
81         for i := 0; i < pointCount; i++ {
82                 points = append(points, randomPoint(r))
83         }
84         log.Printf("Traversing %d points.", len(points))
85         stream, err := client.RecordRoute(context.Background())
86         if err != nil {
87                 log.Fatalf("%v.RecordRoute(_) = _, %v", client, err)
88         }
89         for _, point := range points {
90                 if err := stream.Send(point); err != nil {
91                         log.Fatalf("%v.Send(%v) = %v", stream, point, err)
92                 }
93         }
94         reply, err := stream.CloseAndRecv()
95         if err != nil {
96                 log.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil)
97         }
98         log.Printf("Route summary: %v", reply)
99 }
100
101 // runRouteChat receives a sequence of route notes, while sending notes for various locations.
102 func runRouteChat(client pb.RouteGuideClient) {
103         notes := []*pb.RouteNote{
104                 {&pb.Point{Latitude: 0, Longitude: 1}, "First message"},
105                 {&pb.Point{Latitude: 0, Longitude: 2}, "Second message"},
106                 {&pb.Point{Latitude: 0, Longitude: 3}, "Third message"},
107                 {&pb.Point{Latitude: 0, Longitude: 1}, "Fourth message"},
108                 {&pb.Point{Latitude: 0, Longitude: 2}, "Fifth message"},
109                 {&pb.Point{Latitude: 0, Longitude: 3}, "Sixth message"},
110         }
111         stream, err := client.RouteChat(context.Background())
112         if err != nil {
113                 log.Fatalf("%v.RouteChat(_) = _, %v", client, err)
114         }
115         waitc := make(chan struct{})
116         go func() {
117                 for {
118                         in, err := stream.Recv()
119                         if err == io.EOF {
120                                 // read done.
121                                 close(waitc)
122                                 return
123                         }
124                         if err != nil {
125                                 log.Fatalf("Failed to receive a note : %v", err)
126                         }
127                         log.Printf("Got message %s at point(%d, %d)", in.Message, in.Location.Latitude, in.Location.Longitude)
128                 }
129         }()
130         for _, note := range notes {
131                 if err := stream.Send(note); err != nil {
132                         log.Fatalf("Failed to send a note: %v", err)
133                 }
134         }
135         stream.CloseSend()
136         <-waitc
137 }
138
139 func randomPoint(r *rand.Rand) *pb.Point {
140         lat := (r.Int31n(180) - 90) * 1e7
141         long := (r.Int31n(360) - 180) * 1e7
142         return &pb.Point{Latitude: lat, Longitude: long}
143 }
144
145 func main() {
146         flag.Parse()
147         var opts []grpc.DialOption
148         if *tls {
149                 if *caFile == "" {
150                         *caFile = testdata.Path("ca.pem")
151                 }
152                 creds, err := credentials.NewClientTLSFromFile(*caFile, *serverHostOverride)
153                 if err != nil {
154                         log.Fatalf("Failed to create TLS credentials %v", err)
155                 }
156                 opts = append(opts, grpc.WithTransportCredentials(creds))
157         } else {
158                 opts = append(opts, grpc.WithInsecure())
159         }
160         conn, err := grpc.Dial(*serverAddr, opts...)
161         if err != nil {
162                 log.Fatalf("fail to dial: %v", err)
163         }
164         defer conn.Close()
165         client := pb.NewRouteGuideClient(conn)
166
167         // Looking for a valid feature
168         printFeature(client, &pb.Point{Latitude: 409146138, Longitude: -746188906})
169
170         // Feature missing.
171         printFeature(client, &pb.Point{Latitude: 0, Longitude: 0})
172
173         // Looking for features between 40, -75 and 42, -73.
174         printFeatures(client, &pb.Rectangle{
175                 Lo: &pb.Point{Latitude: 400000000, Longitude: -750000000},
176                 Hi: &pb.Point{Latitude: 420000000, Longitude: -730000000},
177         })
178
179         // RecordRoute
180         runRecordRoute(client)
181
182         // RouteChat
183         runRouteChat(client)
184 }