EchoViewController.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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.channel.host = "example.com" // sample override
  116. }
  117. }
  118. func callServer(address:String, host:String) throws -> Void {
  119. prepareService(address:address, host:host)
  120. let requestMetadata = Metadata(["x-goog-api-key":"YOUR_API_KEY",
  121. "x-ios-bundle-identifier":Bundle.main.bundleIdentifier!])
  122. if (self.callSelectButton.selectedSegment == 0) {
  123. // NONSTREAMING
  124. if let service = service {
  125. var requestMessage = Echo_EchoRequest()
  126. requestMessage.text = self.messageField.stringValue
  127. self.displayMessageSent(requestMessage.text)
  128. // service.get() is a blocking call
  129. DispatchQueue.global().async {
  130. let result = service.get(requestMessage)
  131. switch result {
  132. case .Response(let responseMessage):
  133. self.displayMessageReceived(responseMessage.text)
  134. case .CallResult(let result):
  135. self.displayMessageReceived("No message received. \(result)")
  136. case .Error(let error):
  137. self.displayMessageReceived("No message received. \(error)")
  138. }
  139. }
  140. }
  141. }
  142. else if (self.callSelectButton.selectedSegment == 1) {
  143. // STREAMING EXPAND
  144. if (!nowStreaming) {
  145. guard let service = service else {
  146. return
  147. }
  148. var requestMessage = Echo_EchoRequest()
  149. requestMessage.text = self.messageField.stringValue
  150. self.expandCall = service.expand(requestMessage)
  151. self.displayMessageSent(requestMessage.text)
  152. try! self.receiveExpandMessage()
  153. }
  154. }
  155. else if (self.callSelectButton.selectedSegment == 2) {
  156. // STREAMING COLLECT
  157. if (!nowStreaming) {
  158. guard let service = service else {
  159. return
  160. }
  161. collectCall = service.collect()
  162. nowStreaming = true
  163. closeButton.isEnabled = true
  164. }
  165. self.sendCollectMessage()
  166. }
  167. else if (self.callSelectButton.selectedSegment == 3) {
  168. // STREAMING UPDATE
  169. if (!nowStreaming) {
  170. guard let service = service else {
  171. return
  172. }
  173. updateCall = service.update()
  174. try self.receiveUpdateMessage()
  175. nowStreaming = true
  176. closeButton.isEnabled = true
  177. }
  178. self.sendUpdateMessage()
  179. }
  180. }
  181. func receiveExpandMessage() throws -> Void {
  182. guard let expandCall = expandCall else {
  183. return
  184. }
  185. DispatchQueue.global().async {
  186. var running = true
  187. while running {
  188. let result = expandCall.Receive()
  189. switch result {
  190. case .Response(let responseMessage):
  191. self.displayMessageReceived(responseMessage.text)
  192. case .CallResult(let result):
  193. self.displayMessageReceived("No message received. \(result)")
  194. running = false
  195. case .Error(let error):
  196. self.displayMessageReceived("No message received. \(error)")
  197. running = false
  198. }
  199. }
  200. }
  201. }
  202. func sendCollectMessage() {
  203. if let collectCall = collectCall {
  204. var requestMessage = Echo_EchoRequest()
  205. requestMessage.text = self.messageField.stringValue
  206. self.displayMessageSent(requestMessage.text)
  207. _ = collectCall.Send(requestMessage)
  208. }
  209. }
  210. func sendUpdateMessage() {
  211. if let updateCall = updateCall {
  212. var requestMessage = Echo_EchoRequest()
  213. requestMessage.text = self.messageField.stringValue
  214. self.displayMessageSent(requestMessage.text)
  215. _ = updateCall.Send(message:requestMessage)
  216. }
  217. }
  218. func receiveUpdateMessage() throws -> Void {
  219. guard let updateCall = updateCall else {
  220. return
  221. }
  222. DispatchQueue.global().async {
  223. var running = true
  224. while running {
  225. let result = updateCall.Receive()
  226. switch result {
  227. case .Response(let responseMessage):
  228. self.displayMessageReceived(responseMessage.text)
  229. case .CallResult(let result):
  230. self.displayMessageReceived("No message received. \(result)")
  231. running = false
  232. case .Error(let error):
  233. self.displayMessageReceived("No message received. \(error)")
  234. running = false
  235. }
  236. }
  237. }
  238. }
  239. func sendClose() throws {
  240. if let updateCall = updateCall {
  241. updateCall.CloseSend()
  242. self.updateCall = nil
  243. self.nowStreaming = false
  244. self.closeButton.isEnabled = false
  245. }
  246. if let collectCall = collectCall {
  247. let result = collectCall.CloseAndReceive()
  248. switch result {
  249. case .Response(let responseMessage):
  250. self.displayMessageReceived(responseMessage.text)
  251. case .CallResult(let result):
  252. self.displayMessageReceived("No message received. \(result)")
  253. case .Error(let error):
  254. self.displayMessageReceived("No message received. \(error)")
  255. }
  256. self.collectCall = nil
  257. self.nowStreaming = false
  258. self.closeButton.isEnabled = false
  259. }
  260. }
  261. }