client-call-bidistreaming.swift 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /// {{ method.name }} (Bidirectional 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. let sem = DispatchSemaphore(value: 0)
  11. try self.call.start(.bidiStreaming,
  12. metadata:metadata)
  13. {callResult in
  14. sem.signal()
  15. }
  16. _ = sem.wait(timeout: DispatchTime.distantFuture)
  17. return self
  18. }
  19. /// Call this to wait for a result. Blocks.
  20. public func receive() throws -> {{ method|output }} {
  21. var returnError : {{ .|clienterror:protoFile,service }}?
  22. var returnMessage : {{ method|output }}!
  23. let sem = DispatchSemaphore(value: 0)
  24. do {
  25. try call.receiveMessage() {(data) in
  26. if let data = data {
  27. returnMessage = try? {{ method|output }}(protobuf:data)
  28. if returnMessage == nil {
  29. returnError = {{ .|clienterror:protoFile,service }}.invalidMessageReceived
  30. }
  31. } else {
  32. returnError = {{ .|clienterror:protoFile,service }}.endOfStream
  33. }
  34. sem.signal()
  35. }
  36. _ = sem.wait(timeout: DispatchTime.distantFuture)
  37. }
  38. if let returnError = returnError {
  39. throw returnError
  40. }
  41. return returnMessage
  42. }
  43. /// Call this to send each message in the request stream.
  44. public func send(_ message:{{ method|input }}) throws {
  45. let messageData = try message.serializeProtobuf()
  46. try call.sendMessage(data:messageData)
  47. }
  48. /// Call this to close the sending connection.
  49. public func closeSend() throws {
  50. let sem = DispatchSemaphore(value: 0)
  51. try call.close() {
  52. sem.signal()
  53. }
  54. _ = sem.wait(timeout: DispatchTime.distantFuture)
  55. }
  56. }