client-call-bidistreaming.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. Nonblocking.
  9. fileprivate func start(metadata:Metadata, completion:@escaping (CallResult)->())
  10. throws -> {{ .|call:protoFile,service,method }} {
  11. try self.call.start(.bidiStreaming, metadata:metadata, completion:completion)
  12. return self
  13. }
  14. /// Call this to wait for a result. Blocks.
  15. public func receive() throws -> {{ method|output }} {
  16. var returnError : {{ .|clienterror:protoFile,service }}?
  17. var returnMessage : {{ method|output }}!
  18. let sem = DispatchSemaphore(value: 0)
  19. do {
  20. try call.receiveMessage() {(data) in
  21. if let data = data {
  22. returnMessage = try? {{ method|output }}(protobuf:data)
  23. if returnMessage == nil {
  24. returnError = {{ .|clienterror:protoFile,service }}.invalidMessageReceived
  25. }
  26. } else {
  27. returnError = {{ .|clienterror:protoFile,service }}.endOfStream
  28. }
  29. sem.signal()
  30. }
  31. _ = sem.wait(timeout: DispatchTime.distantFuture)
  32. }
  33. if let returnError = returnError {
  34. throw returnError
  35. }
  36. return returnMessage
  37. }
  38. /// Call this to wait for a result. Nonblocking.
  39. public func receive(completion:@escaping ({{ method|output }}?, {{ .|clienterror:protoFile,service }}?)->()) throws {
  40. do {
  41. try call.receiveMessage() {(data) in
  42. if let data = data {
  43. if let returnMessage = try? {{ method|output }}(protobuf:data) {
  44. completion(returnMessage, nil)
  45. } else {
  46. completion(nil, {{ .|clienterror:protoFile,service }}.invalidMessageReceived)
  47. }
  48. } else {
  49. completion(nil, {{ .|clienterror:protoFile,service }}.endOfStream)
  50. }
  51. }
  52. }
  53. }
  54. /// Call this to send each message in the request stream.
  55. public func send(_ message:{{ method|input }}) throws {
  56. let messageData = try message.serializeProtobuf()
  57. try call.sendMessage(data:messageData)
  58. }
  59. /// Call this to close the sending connection. Blocking
  60. public func closeSend() throws {
  61. let sem = DispatchSemaphore(value: 0)
  62. try call.close() {
  63. sem.signal()
  64. }
  65. _ = sem.wait(timeout: DispatchTime.distantFuture)
  66. }
  67. /// Call this to close the sending connection. Nonblocking
  68. public func closeSend(completion:@escaping ()->()) throws {
  69. try call.close() {
  70. completion()
  71. }
  72. }
  73. }