main.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. #if compiler(>=5.6)
  17. import ArgumentParser
  18. import struct Foundation.Data
  19. import struct Foundation.URL
  20. import GRPC
  21. import NIOCore
  22. import NIOPosix
  23. import RouteGuideModel
  24. /// Loads the features from `route_guide_db.json`, assumed to be in the directory above this file.
  25. func loadFeatures() throws -> [Routeguide_Feature] {
  26. let url = URL(fileURLWithPath: #file)
  27. .deletingLastPathComponent() // main.swift
  28. .deletingLastPathComponent() // Server/
  29. .appendingPathComponent("route_guide_db.json")
  30. let data = try Data(contentsOf: url)
  31. return try Routeguide_Feature.array(fromJSONUTF8Data: data)
  32. }
  33. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  34. struct RouteGuide: ParsableCommand {
  35. @Option(help: "The port to listen on for new connections")
  36. var port = 1234
  37. func run() throws {
  38. // Create an event loop group for the server to run on.
  39. let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
  40. defer {
  41. try! group.syncShutdownGracefully()
  42. }
  43. // Read the feature database.
  44. let features = try loadFeatures()
  45. // Create a provider using the features we read.
  46. let provider = RouteGuideProvider(features: features)
  47. // Start the server and print its address once it has started.
  48. let server = Server.insecure(group: group)
  49. .withServiceProviders([provider])
  50. .bind(host: "localhost", port: self.port)
  51. server.map {
  52. $0.channel.localAddress
  53. }.whenSuccess { address in
  54. print("server started on port \(address!.port!)")
  55. }
  56. // Wait on the server's `onClose` future to stop the program from exiting.
  57. _ = try server.flatMap {
  58. $0.onClose
  59. }.wait()
  60. }
  61. }
  62. if #available(macOS 12, *) {
  63. RouteGuide.main()
  64. } else {
  65. fatalError("The RouteGuide example requires macOS 12 or newer.")
  66. }
  67. #else
  68. fatalError("The RouteGuide example requires Swift concurrency support.")
  69. #endif // compiler(>=5.6)