client-call-clientstreaming.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // {{ method.name }} (Client Streaming)
  2. public class {{ .|call:protoFile,service,method }} {
  3. private var call : Call
  4. /// Create a call.
  5. fileprivate init(_ channel: Channel) {
  6. self.call = channel.makeCall("{{ .|path:protoFile,service,method }}")
  7. }
  8. // Call this to start a call.
  9. fileprivate func run(metadata:Metadata) throws -> {{ .|call:protoFile,service,method }} {
  10. try self.call.start(metadata: metadata)
  11. {_ in}
  12. return self
  13. }
  14. // Call this to send each message in the request stream.
  15. public func Send(_ message: {{ method|input }}) throws {
  16. let messageData = try message.serializeProtobuf()
  17. _ = call.sendMessage(data:messageData)
  18. }
  19. // Call this to close the connection and wait for a response. Blocks.
  20. public func CloseAndReceive() throws -> {{ method|output }} {
  21. var returnError : {{ .|clienterror:protoFile,service }}?
  22. var returnMessage : {{ method|output }}!
  23. let done = NSCondition()
  24. do {
  25. try self.receiveMessage() {(responseMessage) in
  26. if let responseMessage = responseMessage {
  27. returnMessage = responseMessage
  28. } else {
  29. returnError = {{ .|clienterror:protoFile,service }}.invalidMessageReceived
  30. }
  31. done.lock()
  32. done.signal()
  33. done.unlock()
  34. }
  35. try call.close(completion:{
  36. print("closed")
  37. })
  38. done.lock()
  39. done.wait()
  40. done.unlock()
  41. } catch (let error) {
  42. print("ERROR B: \(error)")
  43. }
  44. if let returnError = returnError {
  45. throw returnError
  46. }
  47. return returnMessage
  48. }
  49. // Call this to receive a message.
  50. // The callback will be called when a message is received.
  51. // call this again from the callback to wait for another message.
  52. fileprivate func receiveMessage(callback:@escaping ({{ method|output }}?) throws -> Void)
  53. throws {
  54. try call.receiveMessage() {(data) in
  55. guard let data = data else {
  56. try callback(nil)
  57. return
  58. }
  59. guard
  60. let responseMessage = try? {{ method|output }}(protobuf:data)
  61. else {
  62. return
  63. }
  64. try callback(responseMessage)
  65. }
  66. }
  67. }