main.swift 6.9 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 Foundation
  17. import GRPC
  18. import Logging
  19. import NIO
  20. import RouteGuideModel
  21. /// Makes a `RouteGuide` client for a service hosted on "localhost" and listening on the given port.
  22. func makeClient(port: Int, group: EventLoopGroup) -> Routeguide_RouteGuideClient {
  23. let channel = ClientConnection.insecure(group: group)
  24. .connect(host: "localhost", port: port)
  25. return Routeguide_RouteGuideClient(channel: channel)
  26. }
  27. /// Unary call example. Calls `getFeature` and prints the response.
  28. func getFeature(using client: Routeguide_RouteGuideClient, latitude: Int, longitude: Int) {
  29. print("→ GetFeature: lat=\(latitude) lon=\(longitude)")
  30. let point: Routeguide_Point = .with {
  31. $0.latitude = numericCast(latitude)
  32. $0.longitude = numericCast(longitude)
  33. }
  34. let call = client.getFeature(point)
  35. let feature: Routeguide_Feature
  36. do {
  37. feature = try call.response.wait()
  38. } catch {
  39. print("RPC failed: \(error)")
  40. return
  41. }
  42. let lat = feature.location.latitude
  43. let lon = feature.location.longitude
  44. if !feature.name.isEmpty {
  45. print("Found feature called '\(feature.name)' at \(lat), \(lon)")
  46. } else {
  47. print("Found no feature at \(lat), \(lon)")
  48. }
  49. }
  50. /// Server-streaming example. Calls `listFeatures` with a rectangle of interest. Prints each
  51. /// response feature as it arrives.
  52. func listFeatures(
  53. using client: Routeguide_RouteGuideClient,
  54. lowLatitude: Int,
  55. lowLongitude: Int,
  56. highLatitude: Int,
  57. highLongitude: Int
  58. ) {
  59. print(
  60. "→ ListFeatures: lowLat=\(lowLatitude) lowLon=\(lowLongitude), hiLat=\(highLatitude) hiLon=\(highLongitude)"
  61. )
  62. let rectangle: Routeguide_Rectangle = .with {
  63. $0.lo = .with {
  64. $0.latitude = numericCast(lowLatitude)
  65. $0.longitude = numericCast(lowLongitude)
  66. }
  67. $0.hi = .with {
  68. $0.latitude = numericCast(highLatitude)
  69. $0.longitude = numericCast(highLongitude)
  70. }
  71. }
  72. var resultCount = 1
  73. let call = client.listFeatures(rectangle) { feature in
  74. print("Result #\(resultCount): \(feature)")
  75. resultCount += 1
  76. }
  77. let status = try! call.status.recover { _ in .processingError }.wait()
  78. if status.code != .ok {
  79. print("RPC failed: \(status)")
  80. }
  81. }
  82. /// Client-streaming example. Sends `featuresToVisit` randomly chosen points from `features` with
  83. /// a variable delay in between. Prints the statistics when they are sent from the server.
  84. public func recordRoute(
  85. using client: Routeguide_RouteGuideClient,
  86. features: [Routeguide_Feature],
  87. featuresToVisit: Int
  88. ) {
  89. print("→ RecordRoute")
  90. let options = CallOptions(timeLimit: .timeout(.minutes(1)))
  91. let call = client.recordRoute(callOptions: options)
  92. call.response.whenSuccess { summary in
  93. print(
  94. "Finished trip with \(summary.pointCount) points. Passed \(summary.featureCount) features. " +
  95. "Travelled \(summary.distance) meters. It took \(summary.elapsedTime) seconds."
  96. )
  97. }
  98. call.response.whenFailure { error in
  99. print("RecordRoute Failed: \(error)")
  100. }
  101. call.status.whenComplete { _ in
  102. print("Finished RecordRoute")
  103. }
  104. for _ in 0 ..< featuresToVisit {
  105. let index = Int.random(in: 0 ..< features.count)
  106. let point = features[index].location
  107. print("Visiting point \(point.latitude), \(point.longitude)")
  108. call.sendMessage(point, promise: nil)
  109. // Sleep for a bit before sending the next one.
  110. Thread.sleep(forTimeInterval: TimeInterval.random(in: 0.5 ..< 1.5))
  111. }
  112. call.sendEnd(promise: nil)
  113. // Wait for the call to end.
  114. _ = try! call.status.wait()
  115. }
  116. /// Bidirectional example. Send some chat messages, and print any chat messages that are sent from
  117. /// the server.
  118. func routeChat(using client: Routeguide_RouteGuideClient) {
  119. print("→ RouteChat")
  120. let call = client.routeChat { note in
  121. print(
  122. "Got message \"\(note.message)\" at \(note.location.latitude), \(note.location.longitude)"
  123. )
  124. }
  125. call.status.whenSuccess { status in
  126. if status.code == .ok {
  127. print("Finished RouteChat")
  128. } else {
  129. print("RouteChat Failed: \(status)")
  130. }
  131. }
  132. let noteContent = [
  133. ("First message", 0, 0),
  134. ("Second message", 0, 1),
  135. ("Third message", 1, 0),
  136. ("Fourth message", 1, 1),
  137. ]
  138. for (message, latitude, longitude) in noteContent {
  139. let note: Routeguide_RouteNote = .with {
  140. $0.message = message
  141. $0.location = .with {
  142. $0.latitude = Int32(latitude)
  143. $0.longitude = Int32(longitude)
  144. }
  145. }
  146. print(
  147. "Sending message \"\(note.message)\" at \(note.location.latitude), \(note.location.longitude)"
  148. )
  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 let .some(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: 409_146_138, longitude: -746_188_906)
  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: 400_000_000,
  190. lowLongitude: -750_000_000,
  191. highLatitude: 420_000_000,
  192. highLongitude: -730_000_000
  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)