main.swift 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 NIO
  19. import RouteGuideModel
  20. import Logging
  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("→ ListFeatures: lowLat=\(lowLatitude) lowLon=\(lowLongitude), hiLat=\(highLatitude) hiLon=\(highLongitude)")
  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("Got message \"\(note.message)\" at \(note.location.latitude), \(note.location.longitude)")
  126. }
  127. call.status.whenSuccess { status in
  128. if status.code == .ok {
  129. print("Finished RouteChat")
  130. } else {
  131. print("RouteChat Failed: \(status)")
  132. }
  133. }
  134. let noteContent = [
  135. ("First message", 0, 0),
  136. ("Second message", 0, 1),
  137. ("Third message", 1, 0),
  138. ("Fourth message", 1, 1)
  139. ]
  140. for (message, latitude, longitude) in noteContent {
  141. let note: Routeguide_RouteNote = .with {
  142. $0.message = message
  143. $0.location = .with {
  144. $0.latitude = Int32(latitude)
  145. $0.longitude = Int32(longitude)
  146. }
  147. }
  148. print("Sending message \"\(note.message)\" at \(note.location.latitude), \(note.location.longitude)")
  149. call.sendMessage(note, promise: nil)
  150. }
  151. // Mark the end of the stream.
  152. call.sendEnd(promise: nil)
  153. // Wait for the call to end.
  154. _ = try! call.status.wait()
  155. }
  156. /// Loads the features from `route_guide_db.json`, assumed to be in the directory above this file.
  157. func loadFeatures() throws -> [Routeguide_Feature] {
  158. let url = URL(fileURLWithPath: #file)
  159. .deletingLastPathComponent() // main.swift
  160. .deletingLastPathComponent() // Client/
  161. .appendingPathComponent("route_guide_db.json")
  162. let data = try Data(contentsOf: url)
  163. return try Routeguide_Feature.array(fromJSONUTF8Data: data)
  164. }
  165. func main(args: [String]) throws {
  166. // arg0 (dropped) is the program name. We expect arg1 to be the port.
  167. guard case .some(let port) = args.dropFirst(1).first.flatMap(Int.init) else {
  168. print("Usage: \(args[0]) PORT")
  169. exit(1)
  170. }
  171. // Load the features.
  172. let features = try loadFeatures()
  173. let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  174. defer {
  175. try? group.syncShutdownGracefully()
  176. }
  177. // Make a client, make sure we close it when we're done.
  178. let routeGuide = makeClient(port: port, group: group)
  179. defer {
  180. try? routeGuide.channel.close().wait()
  181. }
  182. // Look for a valid feature.
  183. getFeature(using: routeGuide, latitude: 409146138, longitude: -746188906)
  184. // Look for a missing feature.
  185. getFeature(using: routeGuide, latitude: 0, longitude: 0)
  186. // Looking for features between 40, -75 and 42, -73.
  187. listFeatures(
  188. using: routeGuide,
  189. lowLatitude: 400000000,
  190. lowLongitude: -750000000,
  191. highLatitude: 420000000,
  192. highLongitude: -730000000
  193. )
  194. // Record a few randomly selected points from the features file.
  195. recordRoute(using: routeGuide, features: features, featuresToVisit: 10)
  196. // Send and receive some notes.
  197. routeChat(using: routeGuide)
  198. }
  199. try main(args: CommandLine.arguments)