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