main.swift 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 Foundation
  18. import GRPC
  19. import Logging
  20. import NIO
  21. import RouteGuideModel
  22. import SwiftProtobuf
  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: #file)
  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. struct RouteGuide: ParsableCommand {
  33. @Option(help: "The port to listen on for new connections")
  34. var port = 1234
  35. func run() throws {
  36. // Create an event loop group for the server to run on.
  37. let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
  38. defer {
  39. try! group.syncShutdownGracefully()
  40. }
  41. // Read the feature database.
  42. let features = try loadFeatures()
  43. // Create a provider using the features we read.
  44. let provider = RouteGuideProvider(features: features)
  45. // Start the server and print its address once it has started.
  46. let server = Server.insecure(group: group)
  47. .withServiceProviders([provider])
  48. .bind(host: "localhost", port: self.port)
  49. server.map {
  50. $0.channel.localAddress
  51. }.whenSuccess { address in
  52. print("server started on port \(address!.port!)")
  53. }
  54. // Wait on the server's `onClose` future to stop the program from exiting.
  55. _ = try server.flatMap {
  56. $0.onClose
  57. }.wait()
  58. }
  59. }
  60. RouteGuide.main()