main.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 RouteGuideModel
  19. import NIO
  20. import Logging
  21. import SwiftProtobuf
  22. // Quieten the logs.
  23. LoggingSystem.bootstrap {
  24. var handler = StreamLogHandler.standardOutput(label: $0)
  25. handler.logLevel = .critical
  26. return handler
  27. }
  28. /// Loads the features from `route_guide_db.json`, assumed to be in the directory above this file.
  29. func loadFeatures() throws -> [Routeguide_Feature] {
  30. let url = URL(fileURLWithPath: #file)
  31. .deletingLastPathComponent() // main.swift
  32. .deletingLastPathComponent() // Server/
  33. .appendingPathComponent("route_guide_db.json")
  34. let data = try Data(contentsOf: url)
  35. return try Routeguide_Feature.array(fromJSONUTF8Data: data)
  36. }
  37. func main(args: [String]) 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. // Tie these together in some configuration:
  48. let configuration = Server.Configuration(
  49. target: .hostAndPort("localhost", 0),
  50. eventLoopGroup: group,
  51. serviceProviders: [provider]
  52. )
  53. // Start the server and print its address once it has started.
  54. let server = Server.start(configuration: configuration)
  55. server.map {
  56. $0.channel.localAddress
  57. }.whenSuccess { address in
  58. print("server started on port \(address!.port!)")
  59. }
  60. // Wait on the server's `onClose` future to stop the program from exiting.
  61. _ = try server.flatMap {
  62. $0.onClose
  63. }.wait()
  64. }
  65. try main(args: CommandLine.arguments)