EchoProvider.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright 2016, 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 Foundation
  17. class EchoProvider : Echo_EchoProvider {
  18. // get returns requests as they were received.
  19. func get(request : Echo_EchoRequest, session : Echo_EchoGetSession) throws -> Echo_EchoResponse {
  20. var response = Echo_EchoResponse()
  21. response.text = "Swift echo get: " + request.text
  22. return response
  23. }
  24. // expand splits a request into words and returns each word in a separate message.
  25. func expand(request : Echo_EchoRequest, session : Echo_EchoExpandSession) throws -> Void {
  26. let parts = request.text.components(separatedBy: " ")
  27. var i = 0
  28. for part in parts {
  29. var response = Echo_EchoResponse()
  30. response.text = "Swift echo expand (\(i)): \(part)"
  31. try session.send(response)
  32. i += 1
  33. sleep(1)
  34. }
  35. }
  36. // collect collects a sequence of messages and returns them concatenated when the caller closes.
  37. func collect(session : Echo_EchoCollectSession) throws -> Void {
  38. var parts : [String] = []
  39. while true {
  40. do {
  41. let request = try session.receive()
  42. parts.append(request.text)
  43. } catch Echo_EchoServerError.endOfStream {
  44. break
  45. } catch (let error) {
  46. print("\(error)")
  47. }
  48. }
  49. var response = Echo_EchoResponse()
  50. response.text = "Swift echo collect: " + parts.joined(separator: " ")
  51. try session.sendAndClose(response)
  52. }
  53. // update streams back messages as they are received in an input stream.
  54. func update(session : Echo_EchoUpdateSession) throws -> Void {
  55. var count = 0
  56. while true {
  57. do {
  58. let request = try session.receive()
  59. count += 1
  60. var response = Echo_EchoResponse()
  61. response.text = "Swift echo update (\(count)): \(request.text)"
  62. try session.send(response)
  63. } catch Echo_EchoServerError.endOfStream {
  64. break
  65. } catch (let error) {
  66. print("\(error)")
  67. }
  68. }
  69. try session.close()
  70. }
  71. }