RouteGuideServer.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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: #filePath)
  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. @main
  34. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  35. struct RouteGuide: AsyncParsableCommand {
  36. @Option(help: "The port to listen on for new connections")
  37. var port = 1234
  38. func run() async throws {
  39. // Create an event loop group for the server to run on.
  40. let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
  41. defer {
  42. try! group.syncShutdownGracefully()
  43. }
  44. // Read the feature database.
  45. let features = try loadFeatures()
  46. // Create a provider using the features we read.
  47. let provider = RouteGuideProvider(features: features)
  48. // Start the server and print its address once it has started.
  49. let server = try await Server.insecure(group: group)
  50. .withServiceProviders([provider])
  51. .bind(host: "localhost", port: self.port)
  52. .get()
  53. print("server started on port \(server.channel.localAddress!.port!)")
  54. // Wait on the server's `onClose` future to stop the program from exiting.
  55. try await server.onClose.get()
  56. }
  57. }
  58. #else
  59. @main
  60. enum RouteGuide {
  61. static func main() {
  62. print("This example requires Swift >= 5.6")
  63. }
  64. }
  65. #endif // compiler(>=5.6)