main.swift 7.1 KB

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