RouteChat.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright 2024, 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 GRPCCore
  18. import GRPCNIOTransportHTTP2
  19. struct RouteChat: AsyncParsableCommand {
  20. static let configuration = CommandConfiguration(
  21. abstract: """
  22. Visits a few points and records a note at each, and prints all notes previously recorded at \
  23. each point.
  24. """
  25. )
  26. @Option(help: "The server's listening port")
  27. var port: Int = 31415
  28. func run() async throws {
  29. try await withGRPCClient(
  30. transport: .http2NIOPosix(
  31. target: .ipv4(host: "127.0.0.1", port: self.port),
  32. transportSecurity: .plaintext
  33. )
  34. ) { client in
  35. let routeGuide = Routeguide_RouteGuide.Client(wrapping: client)
  36. try await routeGuide.routeChat { writer in
  37. let notes: [(String, (Int32, Int32))] = [
  38. ("First message", (0, 0)),
  39. ("Second message", (0, 1)),
  40. ("Third message", (1, 0)),
  41. ("Fourth message", (0, 0)),
  42. ("Fifth message", (1, 0)),
  43. ]
  44. for (message, (lat, lon)) in notes {
  45. let note = Routeguide_RouteNote.with {
  46. $0.message = message
  47. $0.location.latitude = lat
  48. $0.location.longitude = lon
  49. }
  50. print("Sending note: '\(message) at (\(lat), \(lon))'")
  51. try await writer.write(note)
  52. }
  53. } onResponse: { response in
  54. for try await note in response.messages {
  55. let (lat, lon) = (note.location.latitude, note.location.longitude)
  56. print("Received note: '\(note.message) at (\(lat), \(lon))'")
  57. }
  58. }
  59. }
  60. }
  61. }