client.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. // Package main implements a simple gRPC client that demonstrates how to use gRPC-Go libraries
  19. // to perform unary, client streaming, server streaming and full duplex RPCs.
  20. //
  21. // It interacts with the route guide service whose definition can be found in routeguide/route_guide.proto.
  22. package main
  23. import (
  24. "context"
  25. "flag"
  26. "io"
  27. "log"
  28. "math/rand"
  29. "time"
  30. "google.golang.org/grpc"
  31. "google.golang.org/grpc/credentials"
  32. pb "google.golang.org/grpc/examples/route_guide/routeguide"
  33. "google.golang.org/grpc/testdata"
  34. )
  35. var (
  36. tls = flag.Bool("tls", false, "Connection uses TLS if true, else plain TCP")
  37. caFile = flag.String("ca_file", "", "The file containning the CA root cert file")
  38. serverAddr = flag.String("server_addr", "127.0.0.1:10000", "The server address in the format of host:port")
  39. serverHostOverride = flag.String("server_host_override", "x.test.youtube.com", "The server name use to verify the hostname returned by TLS handshake")
  40. )
  41. // printFeature gets the feature for the given point.
  42. func printFeature(client pb.RouteGuideClient, point *pb.Point) {
  43. log.Printf("Getting feature for point (%d, %d)", point.Latitude, point.Longitude)
  44. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  45. defer cancel()
  46. feature, err := client.GetFeature(ctx, point)
  47. if err != nil {
  48. log.Fatalf("%v.GetFeatures(_) = _, %v: ", client, err)
  49. }
  50. log.Println(feature)
  51. }
  52. // printFeatures lists all the features within the given bounding Rectangle.
  53. func printFeatures(client pb.RouteGuideClient, rect *pb.Rectangle) {
  54. log.Printf("Looking for features within %v", rect)
  55. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  56. defer cancel()
  57. stream, err := client.ListFeatures(ctx, rect)
  58. if err != nil {
  59. log.Fatalf("%v.ListFeatures(_) = _, %v", client, err)
  60. }
  61. for {
  62. feature, err := stream.Recv()
  63. if err == io.EOF {
  64. break
  65. }
  66. if err != nil {
  67. log.Fatalf("%v.ListFeatures(_) = _, %v", client, err)
  68. }
  69. log.Println(feature)
  70. }
  71. }
  72. // runRecordRoute sends a sequence of points to server and expects to get a RouteSummary from server.
  73. func runRecordRoute(client pb.RouteGuideClient) {
  74. // Create a random number of random points
  75. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  76. pointCount := int(r.Int31n(100)) + 2 // Traverse at least two points
  77. var points []*pb.Point
  78. for i := 0; i < pointCount; i++ {
  79. points = append(points, randomPoint(r))
  80. }
  81. log.Printf("Traversing %d points.", len(points))
  82. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  83. defer cancel()
  84. stream, err := client.RecordRoute(ctx)
  85. if err != nil {
  86. log.Fatalf("%v.RecordRoute(_) = _, %v", client, err)
  87. }
  88. for _, point := range points {
  89. if err := stream.Send(point); err != nil {
  90. log.Fatalf("%v.Send(%v) = %v", stream, point, err)
  91. }
  92. }
  93. reply, err := stream.CloseAndRecv()
  94. if err != nil {
  95. log.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil)
  96. }
  97. log.Printf("Route summary: %v", reply)
  98. }
  99. // runRouteChat receives a sequence of route notes, while sending notes for various locations.
  100. func runRouteChat(client pb.RouteGuideClient) {
  101. notes := []*pb.RouteNote{
  102. {Location: &pb.Point{Latitude: 0, Longitude: 1}, Message: "First message"},
  103. {Location: &pb.Point{Latitude: 0, Longitude: 2}, Message: "Second message"},
  104. {Location: &pb.Point{Latitude: 0, Longitude: 3}, Message: "Third message"},
  105. {Location: &pb.Point{Latitude: 0, Longitude: 1}, Message: "Fourth message"},
  106. {Location: &pb.Point{Latitude: 0, Longitude: 2}, Message: "Fifth message"},
  107. {Location: &pb.Point{Latitude: 0, Longitude: 3}, Message: "Sixth message"},
  108. }
  109. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  110. defer cancel()
  111. stream, err := client.RouteChat(ctx)
  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. func randomPoint(r *rand.Rand) *pb.Point {
  139. lat := (r.Int31n(180) - 90) * 1e7
  140. long := (r.Int31n(360) - 180) * 1e7
  141. return &pb.Point{Latitude: lat, Longitude: long}
  142. }
  143. func main() {
  144. flag.Parse()
  145. var opts []grpc.DialOption
  146. if *tls {
  147. if *caFile == "" {
  148. *caFile = testdata.Path("ca.pem")
  149. }
  150. creds, err := credentials.NewClientTLSFromFile(*caFile, *serverHostOverride)
  151. if err != nil {
  152. log.Fatalf("Failed to create TLS credentials %v", err)
  153. }
  154. opts = append(opts, grpc.WithTransportCredentials(creds))
  155. } else {
  156. opts = append(opts, grpc.WithInsecure())
  157. }
  158. conn, err := grpc.Dial(*serverAddr, opts...)
  159. if err != nil {
  160. log.Fatalf("fail to dial: %v", err)
  161. }
  162. defer conn.Close()
  163. client := pb.NewRouteGuideClient(conn)
  164. // Looking for a valid feature
  165. printFeature(client, &pb.Point{Latitude: 409146138, Longitude: -746188906})
  166. // Feature missing.
  167. printFeature(client, &pb.Point{Latitude: 0, Longitude: 0})
  168. // Looking for features between 40, -75 and 42, -73.
  169. printFeatures(client, &pb.Rectangle{
  170. Lo: &pb.Point{Latitude: 400000000, Longitude: -750000000},
  171. Hi: &pb.Point{Latitude: 420000000, Longitude: -730000000},
  172. })
  173. // RecordRoute
  174. runRecordRoute(client)
  175. // RouteChat
  176. runRouteChat(client)
  177. }