RouteGuideServer.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 ArgumentParser
  17. import GRPC
  18. import NIOCore
  19. import NIOPosix
  20. import RouteGuideModel
  21. import struct Foundation.Data
  22. import struct Foundation.URL
  23. /// Loads the features from `route_guide_db.json`, assumed to be in the directory above this file.
  24. func loadFeatures() throws -> [Routeguide_Feature] {
  25. let url = URL(fileURLWithPath: #filePath)
  26. .deletingLastPathComponent() // main.swift
  27. .deletingLastPathComponent() // Server/
  28. .appendingPathComponent("route_guide_db.json")
  29. let data = try Data(contentsOf: url)
  30. return try Routeguide_Feature.array(fromJSONUTF8Data: data)
  31. }
  32. @main
  33. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  34. struct RouteGuide: AsyncParsableCommand {
  35. @Option(help: "The port to listen on for new connections")
  36. var port = 1234
  37. func run() async 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 = try await Server.insecure(group: group)
  49. .withServiceProviders([provider])
  50. .bind(host: "localhost", port: self.port)
  51. .get()
  52. print("server started on port \(server.channel.localAddress!.port!)")
  53. // Wait on the server's `onClose` future to stop the program from exiting.
  54. try await server.onClose.get()
  55. }
  56. }