client-call-bidistreaming.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. Blocking.
  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 receive() {response, error in
  21. returnMessage = response
  22. returnError = error
  23. sem.signal()
  24. }
  25. _ = sem.wait(timeout: DispatchTime.distantFuture)
  26. }
  27. if let returnError = returnError {
  28. throw returnError
  29. }
  30. return returnMessage
  31. }
  32. /// Call this to wait for a result. Nonblocking.
  33. public func receive(completion:@escaping ({{ method|output }}?, {{ .|clienterror:protoFile,service }}?)->()) throws {
  34. do {
  35. try call.receiveMessage() {(data) in
  36. if let data = data {
  37. if let returnMessage = try? {{ method|output }}(protobuf:data) {
  38. completion(returnMessage, nil)
  39. } else {
  40. completion(nil, {{ .|clienterror:protoFile,service }}.invalidMessageReceived)
  41. }
  42. } else {
  43. completion(nil, {{ .|clienterror:protoFile,service }}.endOfStream)
  44. }
  45. }
  46. }
  47. }
  48. /// Call this to send each message in the request stream.
  49. public func send(_ message:Echo_EchoRequest, errorHandler:@escaping (Error)->()) throws {
  50. let messageData = try message.serializeProtobuf()
  51. try call.sendMessage(data:messageData, errorHandler:errorHandler)
  52. }
  53. /// Call this to close the sending connection. Blocking.
  54. public func closeSend() throws {
  55. let sem = DispatchSemaphore(value: 0)
  56. try closeSend() {
  57. sem.signal()
  58. }
  59. _ = sem.wait(timeout: DispatchTime.distantFuture)
  60. }
  61. /// Call this to close the sending connection. Nonblocking.
  62. public func closeSend(completion:@escaping ()->()) throws {
  63. try call.close() {
  64. completion()
  65. }
  66. }
  67. }