main.swift 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 Logging
  20. import NIO
  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) -> Routeguide_RouteGuideClient {
  24. let channel = ClientConnection.insecure(group: group)
  25. .connect(host: "localhost", port: port)
  26. return Routeguide_RouteGuideClient(channel: channel)
  27. }
  28. /// Unary call example. Calls `getFeature` and prints the response.
  29. func getFeature(using client: Routeguide_RouteGuideClient, latitude: Int, longitude: Int) {
  30. print("→ GetFeature: lat=\(latitude) lon=\(longitude)")
  31. let point: Routeguide_Point = .with {
  32. $0.latitude = numericCast(latitude)
  33. $0.longitude = numericCast(longitude)
  34. }
  35. let call = client.getFeature(point)
  36. let feature: Routeguide_Feature
  37. do {
  38. feature = try call.response.wait()
  39. } catch {
  40. print("RPC failed: \(error)")
  41. return
  42. }
  43. let lat = feature.location.latitude
  44. let lon = feature.location.longitude
  45. if !feature.name.isEmpty {
  46. print("Found feature called '\(feature.name)' at \(lat), \(lon)")
  47. } else {
  48. print("Found no feature at \(lat), \(lon)")
  49. }
  50. }
  51. /// Server-streaming example. Calls `listFeatures` with a rectangle of interest. Prints each
  52. /// response feature as it arrives.
  53. func listFeatures(
  54. using client: Routeguide_RouteGuideClient,
  55. lowLatitude: Int,
  56. lowLongitude: Int,
  57. highLatitude: Int,
  58. highLongitude: Int
  59. ) {
  60. print(
  61. "→ ListFeatures: lowLat=\(lowLatitude) lowLon=\(lowLongitude), hiLat=\(highLatitude) hiLon=\(highLongitude)"
  62. )
  63. let rectangle: Routeguide_Rectangle = .with {
  64. $0.lo = .with {
  65. $0.latitude = numericCast(lowLatitude)
  66. $0.longitude = numericCast(lowLongitude)
  67. }
  68. $0.hi = .with {
  69. $0.latitude = numericCast(highLatitude)
  70. $0.longitude = numericCast(highLongitude)
  71. }
  72. }
  73. var resultCount = 1
  74. let call = client.listFeatures(rectangle) { feature in
  75. print("Result #\(resultCount): \(feature)")
  76. resultCount += 1
  77. }
  78. let status = try! call.status.recover { _ in .processingError }.wait()
  79. if status.code != .ok {
  80. print("RPC failed: \(status)")
  81. }
  82. }
  83. /// Client-streaming example. Sends `featuresToVisit` randomly chosen points from `features` with
  84. /// a variable delay in between. Prints the statistics when they are sent from the server.
  85. public func recordRoute(
  86. using client: Routeguide_RouteGuideClient,
  87. features: [Routeguide_Feature],
  88. featuresToVisit: Int
  89. ) {
  90. print("→ RecordRoute")
  91. let options = CallOptions(timeLimit: .timeout(.minutes(1)))
  92. let call = client.recordRoute(callOptions: options)
  93. call.response.whenSuccess { summary in
  94. print(
  95. "Finished trip with \(summary.pointCount) points. Passed \(summary.featureCount) features. " +
  96. "Travelled \(summary.distance) meters. It took \(summary.elapsedTime) seconds."
  97. )
  98. }
  99. call.response.whenFailure { error in
  100. print("RecordRoute Failed: \(error)")
  101. }
  102. call.status.whenComplete { _ in
  103. print("Finished RecordRoute")
  104. }
  105. for _ in 0 ..< featuresToVisit {
  106. let index = Int.random(in: 0 ..< features.count)
  107. let point = features[index].location
  108. print("Visiting point \(point.latitude), \(point.longitude)")
  109. call.sendMessage(point, promise: nil)
  110. // Sleep for a bit before sending the next one.
  111. Thread.sleep(forTimeInterval: TimeInterval.random(in: 0.5 ..< 1.5))
  112. }
  113. call.sendEnd(promise: nil)
  114. // Wait for the call to end.
  115. _ = try! call.status.wait()
  116. }
  117. /// Bidirectional example. Send some chat messages, and print any chat messages that are sent from
  118. /// the server.
  119. func routeChat(using client: Routeguide_RouteGuideClient) {
  120. print("→ RouteChat")
  121. let call = client.routeChat { note in
  122. print(
  123. "Got message \"\(note.message)\" at \(note.location.latitude), \(note.location.longitude)"
  124. )
  125. }
  126. call.status.whenSuccess { status in
  127. if status.code == .ok {
  128. print("Finished RouteChat")
  129. } else {
  130. print("RouteChat Failed: \(status)")
  131. }
  132. }
  133. let noteContent = [
  134. ("First message", 0, 0),
  135. ("Second message", 0, 1),
  136. ("Third message", 1, 0),
  137. ("Fourth message", 1, 1),
  138. ]
  139. for (message, latitude, longitude) in noteContent {
  140. let note: Routeguide_RouteNote = .with {
  141. $0.message = message
  142. $0.location = .with {
  143. $0.latitude = Int32(latitude)
  144. $0.longitude = Int32(longitude)
  145. }
  146. }
  147. print(
  148. "Sending message \"\(note.message)\" at \(note.location.latitude), \(note.location.longitude)"
  149. )
  150. call.sendMessage(note, promise: nil)
  151. }
  152. // Mark the end of the stream.
  153. call.sendEnd(promise: nil)
  154. // Wait for the call to end.
  155. _ = try! call.status.wait()
  156. }
  157. /// Loads the features from `route_guide_db.json`, assumed to be in the directory above this file.
  158. func loadFeatures() throws -> [Routeguide_Feature] {
  159. let url = URL(fileURLWithPath: #file)
  160. .deletingLastPathComponent() // main.swift
  161. .deletingLastPathComponent() // Client/
  162. .appendingPathComponent("route_guide_db.json")
  163. let data = try Data(contentsOf: url)
  164. return try Routeguide_Feature.array(fromJSONUTF8Data: data)
  165. }
  166. struct RouteGuide: ParsableCommand {
  167. @Option(help: "The port to connect to")
  168. var port: Int = 1234
  169. func run() throws {
  170. // Load the features.
  171. let features = try loadFeatures()
  172. let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  173. defer {
  174. try? group.syncShutdownGracefully()
  175. }
  176. // Make a client, make sure we close it when we're done.
  177. let routeGuide = makeClient(port: self.port, group: group)
  178. defer {
  179. try? routeGuide.channel.close().wait()
  180. }
  181. // Look for a valid feature.
  182. getFeature(using: routeGuide, latitude: 409_146_138, longitude: -746_188_906)
  183. // Look for a missing feature.
  184. getFeature(using: routeGuide, latitude: 0, longitude: 0)
  185. // Looking for features between 40, -75 and 42, -73.
  186. listFeatures(
  187. using: routeGuide,
  188. lowLatitude: 400_000_000,
  189. lowLongitude: -750_000_000,
  190. highLatitude: 420_000_000,
  191. highLongitude: -730_000_000
  192. )
  193. // Record a few randomly selected points from the features file.
  194. recordRoute(using: routeGuide, features: features, featuresToVisit: 10)
  195. // Send and receive some notes.
  196. routeChat(using: routeGuide)
  197. }
  198. }
  199. RouteGuide.main()