RouteChat.swift 2.3 KB

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