main.swift 7.0 KB

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