2
0

main.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. import SwiftProtobuf
  22. /// Loads the features from `route_guide_db.json`, assumed to be in the directory above this file.
  23. func loadFeatures() throws -> [Routeguide_Feature] {
  24. let url = URL(fileURLWithPath: #file)
  25. .deletingLastPathComponent() // main.swift
  26. .deletingLastPathComponent() // Server/
  27. .appendingPathComponent("route_guide_db.json")
  28. let data = try Data(contentsOf: url)
  29. return try Routeguide_Feature.array(fromJSONUTF8Data: data)
  30. }
  31. func main(args: [String]) throws {
  32. // Create an event loop group for the server to run on.
  33. let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
  34. defer {
  35. try! group.syncShutdownGracefully()
  36. }
  37. // Read the feature database.
  38. let features = try loadFeatures()
  39. // Create a provider using the features we read.
  40. let provider = RouteGuideProvider(features: features)
  41. // Start the server and print its address once it has started.
  42. let server = Server.insecure(group: group)
  43. .withServiceProviders([provider])
  44. .bind(host: "localhost", port: 0)
  45. server.map {
  46. $0.channel.localAddress
  47. }.whenSuccess { address in
  48. print("server started on port \(address!.port!)")
  49. }
  50. // Wait on the server's `onClose` future to stop the program from exiting.
  51. _ = try server.flatMap {
  52. $0.onClose
  53. }.wait()
  54. }
  55. try main(args: CommandLine.arguments)