RouteChat.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. let transport = try HTTP2ClientTransport.Posix(
  30. target: .ipv4(host: "127.0.0.1", port: self.port),
  31. transportSecurity: .plaintext
  32. )
  33. let client = GRPCClient(transport: transport)
  34. try await withThrowingDiscardingTaskGroup { group in
  35. group.addTask {
  36. try await client.run()
  37. }
  38. let routeGuide = Routeguide_RouteGuide.Client(wrapping: client)
  39. try await routeGuide.routeChat { writer in
  40. let notes: [(String, (Int32, Int32))] = [
  41. ("First message", (0, 0)),
  42. ("Second message", (0, 1)),
  43. ("Third message", (1, 0)),
  44. ("Fourth message", (0, 0)),
  45. ("Fifth message", (1, 0)),
  46. ]
  47. for (message, (lat, lon)) in notes {
  48. let note = Routeguide_RouteNote.with {
  49. $0.message = message
  50. $0.location.latitude = lat
  51. $0.location.longitude = lon
  52. }
  53. print("Sending note: '\(message) at (\(lat), \(lon))'")
  54. try await writer.write(note)
  55. }
  56. } onResponse: { response in
  57. for try await note in response.messages {
  58. let (lat, lon) = (note.location.latitude, note.location.longitude)
  59. print("Received note: '\(note.message) at (\(lat), \(lon))'")
  60. }
  61. }
  62. client.beginGracefulShutdown()
  63. }
  64. }
  65. }