main.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 GRPC
  17. import HelloWorldModel
  18. import Logging
  19. import NIO
  20. func greet(name: String?, client greeter: Helloworld_GreeterClient) {
  21. // Form the request with the name, if one was provided.
  22. let request = Helloworld_HelloRequest.with {
  23. $0.name = name ?? ""
  24. }
  25. // Make the RPC call to the server.
  26. let sayHello = greeter.sayHello(request)
  27. // wait() on the response to stop the program from exiting before the response is received.
  28. do {
  29. let response = try sayHello.response.wait()
  30. print("Greeter received: \(response.message)")
  31. } catch {
  32. print("Greeter failed: \(error)")
  33. }
  34. }
  35. func main(args: [String]) {
  36. // arg0 (dropped) is the program name. We expect arg1 to be the port, and arg2 (optional) to be
  37. // the name sent in the request.
  38. let arg1 = args.dropFirst(1).first
  39. let arg2 = args.dropFirst(2).first
  40. switch (arg1.flatMap(Int.init), arg2) {
  41. case (.none, _):
  42. print("Usage: PORT [NAME]")
  43. exit(1)
  44. case let (.some(port), name):
  45. // Setup an `EventLoopGroup` for the connection to run on.
  46. //
  47. // See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups
  48. let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  49. // Make sure the group is shutdown when we're done with it.
  50. defer {
  51. try! group.syncShutdownGracefully()
  52. }
  53. // Configure the channel, we're not using TLS so the connection is `insecure`.
  54. let channel = ClientConnection.insecure(group: group)
  55. .connect(host: "localhost", port: port)
  56. // Close the connection when we're done with it.
  57. defer {
  58. try! channel.close().wait()
  59. }
  60. // Provide the connection to the generated client.
  61. let greeter = Helloworld_GreeterClient(channel: channel)
  62. // Do the greeting.
  63. greet(name: name, client: greeter)
  64. }
  65. }
  66. main(args: CommandLine.arguments)