main.swift 2.3 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 ArgumentParser
  17. import GRPC
  18. import HelloWorldModel
  19. import NIOCore
  20. import NIOPosix
  21. func greet(name: String?, client greeter: Helloworld_GreeterClient) {
  22. // Form the request with the name, if one was provided.
  23. let request = Helloworld_HelloRequest.with {
  24. $0.name = name ?? ""
  25. }
  26. // Make the RPC call to the server.
  27. let sayHello = greeter.sayHello(request)
  28. // wait() on the response to stop the program from exiting before the response is received.
  29. do {
  30. let response = try sayHello.response.wait()
  31. print("Greeter received: \(response.message)")
  32. } catch {
  33. print("Greeter failed: \(error)")
  34. }
  35. }
  36. struct HelloWorld: ParsableCommand {
  37. @Option(help: "The port to connect to")
  38. var port: Int = 1234
  39. @Argument(help: "The name to greet")
  40. var name: String?
  41. func run() throws {
  42. // Setup an `EventLoopGroup` for the connection to run on.
  43. //
  44. // See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups
  45. let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  46. // Make sure the group is shutdown when we're done with it.
  47. defer {
  48. try! group.syncShutdownGracefully()
  49. }
  50. // Configure the channel, we're not using TLS so the connection is `insecure`.
  51. let channel = try GRPCChannelPool.with(
  52. target: .host("localhost", port: self.port),
  53. transportSecurity: .plaintext,
  54. eventLoopGroup: group
  55. )
  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: self.name, client: greeter)
  64. }
  65. }
  66. HelloWorld.main()