main.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. /*
  2. * Copyright 2019, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import ArgumentParser
  17. import Foundation
  18. import GRPC
  19. import NIOCore
  20. import NIOPosix
  21. import RouteGuideModel
  22. /// Makes a `RouteGuide` client for a service hosted on "localhost" and listening on the given port.
  23. func makeClient(port: Int, group: EventLoopGroup) throws -> Routeguide_RouteGuideClient {
  24. let channel = try GRPCChannelPool.with(
  25. target: .host("localhost", port: port),
  26. transportSecurity: .plaintext,
  27. eventLoopGroup: group
  28. )
  29. return Routeguide_RouteGuideClient(channel: channel)
  30. }
  31. /// Unary call example. Calls `getFeature` and prints the response.
  32. func getFeature(using client: Routeguide_RouteGuideClient, latitude: Int, longitude: Int) {
  33. print("→ GetFeature: lat=\(latitude) lon=\(longitude)")
  34. let point: Routeguide_Point = .with {
  35. $0.latitude = numericCast(latitude)
  36. $0.longitude = numericCast(longitude)
  37. }
  38. let call = client.getFeature(point)
  39. let feature: Routeguide_Feature
  40. do {
  41. feature = try call.response.wait()
  42. } catch {
  43. print("RPC failed: \(error)")
  44. return
  45. }
  46. let lat = feature.location.latitude
  47. let lon = feature.location.longitude
  48. if !feature.name.isEmpty {
  49. print("Found feature called '\(feature.name)' at \(lat), \(lon)")
  50. } else {
  51. print("Found no feature at \(lat), \(lon)")
  52. }
  53. }
  54. /// Server-streaming example. Calls `listFeatures` with a rectangle of interest. Prints each
  55. /// response feature as it arrives.
  56. func listFeatures(
  57. using client: Routeguide_RouteGuideClient,
  58. lowLatitude: Int,
  59. lowLongitude: Int,
  60. highLatitude: Int,
  61. highLongitude: Int
  62. ) {
  63. print(
  64. "→ ListFeatures: lowLat=\(lowLatitude) lowLon=\(lowLongitude), hiLat=\(highLatitude) hiLon=\(highLongitude)"
  65. )
  66. let rectangle: Routeguide_Rectangle = .with {
  67. $0.lo = .with {
  68. $0.latitude = numericCast(lowLatitude)
  69. $0.longitude = numericCast(lowLongitude)
  70. }
  71. $0.hi = .with {
  72. $0.latitude = numericCast(highLatitude)
  73. $0.longitude = numericCast(highLongitude)
  74. }
  75. }
  76. var resultCount = 1
  77. let call = client.listFeatures(rectangle) { feature in
  78. print("Result #\(resultCount): \(feature)")
  79. resultCount += 1
  80. }
  81. let status = try! call.status.recover { _ in .processingError }.wait()
  82. if status.code != .ok {
  83. print("RPC failed: \(status)")
  84. }
  85. }
  86. /// Client-streaming example. Sends `featuresToVisit` randomly chosen points from `features` with
  87. /// a variable delay in between. Prints the statistics when they are sent from the server.
  88. public func recordRoute(
  89. using client: Routeguide_RouteGuideClient,
  90. features: [Routeguide_Feature],
  91. featuresToVisit: Int
  92. ) {
  93. print("→ RecordRoute")
  94. let options = CallOptions(timeLimit: .timeout(.minutes(1)))
  95. let call = client.recordRoute(callOptions: options)
  96. call.response.whenSuccess { summary in
  97. print(
  98. "Finished trip with \(summary.pointCount) points. Passed \(summary.featureCount) features. " +
  99. "Travelled \(summary.distance) meters. It took \(summary.elapsedTime) seconds."
  100. )
  101. }
  102. call.response.whenFailure { error in
  103. print("RecordRoute Failed: \(error)")
  104. }
  105. call.status.whenComplete { _ in
  106. print("Finished RecordRoute")
  107. }
  108. for _ in 0 ..< featuresToVisit {
  109. let index = Int.random(in: 0 ..< features.count)
  110. let point = features[index].location
  111. print("Visiting point \(point.latitude), \(point.longitude)")
  112. call.sendMessage(point, promise: nil)
  113. // Sleep for a bit before sending the next one.
  114. Thread.sleep(forTimeInterval: TimeInterval.random(in: 0.5 ..< 1.5))
  115. }
  116. call.sendEnd(promise: nil)
  117. // Wait for the call to end.
  118. _ = try! call.status.wait()
  119. }
  120. /// Bidirectional example. Send some chat messages, and print any chat messages that are sent from
  121. /// the server.
  122. func routeChat(using client: Routeguide_RouteGuideClient) {
  123. print("→ RouteChat")
  124. let call = client.routeChat { note in
  125. print(
  126. "Got message \"\(note.message)\" at \(note.location.latitude), \(note.location.longitude)"
  127. )
  128. }
  129. call.status.whenSuccess { status in
  130. if status.code == .ok {
  131. print("Finished RouteChat")
  132. } else {
  133. print("RouteChat Failed: \(status)")
  134. }
  135. }
  136. let noteContent = [
  137. ("First message", 0, 0),
  138. ("Second message", 0, 1),
  139. ("Third message", 1, 0),
  140. ("Fourth message", 1, 1),
  141. ]
  142. for (message, latitude, longitude) in noteContent {
  143. let note: Routeguide_RouteNote = .with {
  144. $0.message = message
  145. $0.location = .with {
  146. $0.latitude = Int32(latitude)
  147. $0.longitude = Int32(longitude)
  148. }
  149. }
  150. print(
  151. "Sending message \"\(note.message)\" at \(note.location.latitude), \(note.location.longitude)"
  152. )
  153. call.sendMessage(note, promise: nil)
  154. }
  155. // Mark the end of the stream.
  156. call.sendEnd(promise: nil)
  157. // Wait for the call to end.
  158. _ = try! call.status.wait()
  159. }
  160. /// Loads the features from `route_guide_db.json`, assumed to be in the directory above this file.
  161. func loadFeatures() throws -> [Routeguide_Feature] {
  162. let url = URL(fileURLWithPath: #file)
  163. .deletingLastPathComponent() // main.swift
  164. .deletingLastPathComponent() // Client/
  165. .appendingPathComponent("route_guide_db.json")
  166. let data = try Data(contentsOf: url)
  167. return try Routeguide_Feature.array(fromJSONUTF8Data: data)
  168. }
  169. struct RouteGuide: ParsableCommand {
  170. @Option(help: "The port to connect to")
  171. var port: Int = 1234
  172. func run() throws {
  173. // Load the features.
  174. let features = try loadFeatures()
  175. let group = PlatformSupport.makeEventLoopGroup(loopCount: 1)
  176. defer {
  177. try? group.syncShutdownGracefully()
  178. }
  179. // Make a client, make sure we close it when we're done.
  180. let routeGuide = try makeClient(port: self.port, group: group)
  181. defer {
  182. try? routeGuide.channel.close().wait()
  183. }
  184. // Look for a valid feature.
  185. getFeature(using: routeGuide, latitude: 409_146_138, longitude: -746_188_906)
  186. // Look for a missing feature.
  187. getFeature(using: routeGuide, latitude: 0, longitude: 0)
  188. // Looking for features between 40, -75 and 42, -73.
  189. listFeatures(
  190. using: routeGuide,
  191. lowLatitude: 400_000_000,
  192. lowLongitude: -750_000_000,
  193. highLatitude: 420_000_000,
  194. highLongitude: -730_000_000
  195. )
  196. // Record a few randomly selected points from the features file.
  197. recordRoute(using: routeGuide, features: features, featuresToVisit: 10)
  198. // Send and receive some notes.
  199. routeChat(using: routeGuide)
  200. }
  201. }
  202. RouteGuide.main()