HelloWorldClient.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  22. @main
  23. struct HelloWorld: AsyncParsableCommand {
  24. @Option(help: "The port to connect to")
  25. var port: Int = 1234
  26. @Argument(help: "The name to greet")
  27. var name: String?
  28. func run() async throws {
  29. // Setup an `EventLoopGroup` for the connection to run on.
  30. //
  31. // See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups
  32. let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  33. // Make sure the group is shutdown when we're done with it.
  34. defer {
  35. try! group.syncShutdownGracefully()
  36. }
  37. // Configure the channel, we're not using TLS so the connection is `insecure`.
  38. let channel = try GRPCChannelPool.with(
  39. target: .host("localhost", port: self.port),
  40. transportSecurity: .plaintext,
  41. eventLoopGroup: group
  42. )
  43. // Close the connection when we're done with it.
  44. defer {
  45. try! channel.close().wait()
  46. }
  47. // Provide the connection to the generated client.
  48. let greeter = Helloworld_GreeterAsyncClient(channel: channel)
  49. // Form the request with the name, if one was provided.
  50. let request = Helloworld_HelloRequest.with {
  51. $0.name = self.name ?? ""
  52. }
  53. do {
  54. let greeting = try await greeter.sayHello(request)
  55. print("Greeter received: \(greeting.message)")
  56. } catch {
  57. print("Greeter failed: \(error)")
  58. }
  59. }
  60. }