EchoViewController.swift 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. /*
  2. *
  3. * Copyright 2016, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. import AppKit
  34. import gRPC
  35. class EchoViewController : NSViewController, NSTextFieldDelegate {
  36. @IBOutlet weak var messageField: NSTextField!
  37. @IBOutlet weak var sentOutputField: NSTextField!
  38. @IBOutlet weak var receivedOutputField: NSTextField!
  39. @IBOutlet weak var addressField: NSTextField!
  40. @IBOutlet weak var TLSButton: NSButton!
  41. @IBOutlet weak var callSelectButton: NSSegmentedControl!
  42. @IBOutlet weak var closeButton: NSButton!
  43. private var service : Echo_EchoService?
  44. private var expandCall: Echo_EchoExpandCall?
  45. private var collectCall: Echo_EchoCollectCall?
  46. private var updateCall: Echo_EchoUpdateCall?
  47. private var nowStreaming = false
  48. required init?(coder:NSCoder) {
  49. super.init(coder:coder)
  50. }
  51. private var enabled = false
  52. @IBAction func messageReturnPressed(sender: NSTextField) {
  53. if enabled {
  54. do {
  55. try callServer(address:addressField.stringValue,
  56. host:"example.com")
  57. } catch (let error) {
  58. print(error)
  59. }
  60. }
  61. }
  62. @IBAction func addressReturnPressed(sender: NSTextField) {
  63. if (nowStreaming) {
  64. if let error = try? self.sendClose() {
  65. print(error)
  66. }
  67. }
  68. // invalidate the service
  69. service = nil
  70. }
  71. @IBAction func buttonValueChanged(sender: NSSegmentedControl) {
  72. if (nowStreaming) {
  73. if let error = try? self.sendClose() {
  74. print(error)
  75. }
  76. }
  77. }
  78. @IBAction func closeButtonPressed(sender: NSButton) {
  79. if (nowStreaming) {
  80. if let error = try? self.sendClose() {
  81. print(error)
  82. }
  83. }
  84. }
  85. override func viewDidLoad() {
  86. closeButton.isEnabled = false
  87. // prevent the UI from trying to send messages until gRPC is initialized
  88. DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
  89. self.enabled = true
  90. }
  91. }
  92. func displayMessageSent(_ message:String) {
  93. DispatchQueue.main.async {
  94. self.sentOutputField.stringValue = message
  95. }
  96. }
  97. func displayMessageReceived(_ message:String) {
  98. DispatchQueue.main.async {
  99. self.receivedOutputField.stringValue = message
  100. }
  101. }
  102. func prepareService(address: String, host: String) {
  103. if (service != nil) {
  104. return
  105. }
  106. if (TLSButton.intValue == 0) {
  107. service = Echo_EchoService(address:address)
  108. } else {
  109. let certificateURL = Bundle.main.url(forResource: "ssl",
  110. withExtension: "crt")!
  111. let certificates = try! String(contentsOf: certificateURL)
  112. service = Echo_EchoService(address:address, certificates:certificates, host:host)
  113. }
  114. if let service = service {
  115. service.host = "example.com" // sample override
  116. service.metadata = Metadata(["x-goog-api-key":"YOUR_API_KEY",
  117. "x-ios-bundle-identifier":Bundle.main.bundleIdentifier!])
  118. }
  119. }
  120. func callServer(address:String, host:String) throws -> Void {
  121. prepareService(address:address, host:host)
  122. guard let service = service else {
  123. return
  124. }
  125. if (self.callSelectButton.selectedSegment == 0) {
  126. // NONSTREAMING
  127. let requestMessage = Echo_EchoRequest(text:self.messageField.stringValue)
  128. self.displayMessageSent(requestMessage.text)
  129. // run this asynchronously because service.get() is a blocking call
  130. DispatchQueue.global().async {
  131. do {
  132. let responseMessage = try service.get(requestMessage)
  133. self.displayMessageReceived(responseMessage.text)
  134. } catch (let error) {
  135. self.displayMessageReceived("No message received. \(error)")
  136. }
  137. }
  138. }
  139. else if (self.callSelectButton.selectedSegment == 1) {
  140. // STREAMING EXPAND
  141. if (!nowStreaming) {
  142. let requestMessage = Echo_EchoRequest(text:self.messageField.stringValue)
  143. self.expandCall = try service.expand(requestMessage)
  144. self.displayMessageSent(requestMessage.text)
  145. try self.receiveExpandMessages()
  146. }
  147. }
  148. else if (self.callSelectButton.selectedSegment == 2) {
  149. // STREAMING COLLECT
  150. if (!nowStreaming) {
  151. collectCall = try service.collect()
  152. nowStreaming = true
  153. closeButton.isEnabled = true
  154. }
  155. try self.sendCollectMessage()
  156. }
  157. else if (self.callSelectButton.selectedSegment == 3) {
  158. // STREAMING UPDATE
  159. if (!nowStreaming) {
  160. updateCall = try service.update()
  161. try self.receiveUpdateMessages()
  162. nowStreaming = true
  163. closeButton.isEnabled = true
  164. }
  165. try self.sendUpdateMessage()
  166. }
  167. }
  168. func receiveExpandMessages() throws -> Void {
  169. guard let expandCall = expandCall else {
  170. return
  171. }
  172. DispatchQueue.global().async {
  173. var running = true
  174. while running {
  175. do {
  176. let responseMessage = try expandCall.Receive()
  177. self.displayMessageReceived(responseMessage.text)
  178. } catch Echo_EchoClientError.endOfStream {
  179. self.displayMessageReceived("Done.")
  180. running = false
  181. } catch (let error) {
  182. self.displayMessageReceived("No message received. \(error)")
  183. }
  184. }
  185. }
  186. }
  187. func sendCollectMessage() throws {
  188. if let collectCall = collectCall {
  189. let requestMessage = Echo_EchoRequest(text:self.messageField.stringValue)
  190. self.displayMessageSent(requestMessage.text)
  191. try collectCall.Send(requestMessage)
  192. }
  193. }
  194. func sendUpdateMessage() throws {
  195. if let updateCall = updateCall {
  196. let requestMessage = Echo_EchoRequest(text:self.messageField.stringValue)
  197. self.displayMessageSent(requestMessage.text)
  198. try updateCall.Send(requestMessage)
  199. }
  200. }
  201. func receiveUpdateMessages() throws -> Void {
  202. guard let updateCall = updateCall else {
  203. return
  204. }
  205. DispatchQueue.global().async {
  206. var running = true
  207. while running {
  208. do {
  209. let responseMessage = try updateCall.Receive()
  210. self.displayMessageReceived(responseMessage.text)
  211. } catch Echo_EchoClientError.endOfStream {
  212. self.displayMessageReceived("Done.")
  213. running = false
  214. } catch (let error) {
  215. self.displayMessageReceived("No message received. \(error)")
  216. }
  217. }
  218. }
  219. }
  220. func sendClose() throws {
  221. if let updateCall = updateCall {
  222. try updateCall.CloseSend()
  223. self.updateCall = nil
  224. self.nowStreaming = false
  225. self.closeButton.isEnabled = false
  226. }
  227. if let collectCall = collectCall {
  228. do {
  229. let responseMessage = try collectCall.CloseAndReceive()
  230. self.displayMessageReceived(responseMessage.text)
  231. } catch (let error) {
  232. self.displayMessageReceived("No message received. \(error)")
  233. }
  234. self.collectCall = nil
  235. self.nowStreaming = false
  236. self.closeButton.isEnabled = false
  237. }
  238. }
  239. }