EchoViewController.swift 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 : EchoService?
  44. private var expandCall: EchoExpandCall?
  45. private var collectCall: EchoCollectCall?
  46. private var updateCall: 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. gRPC.initialize()
  87. closeButton.isEnabled = false
  88. // prevent the UI from trying to send messages until gRPC is initialized
  89. DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
  90. self.enabled = true
  91. }
  92. }
  93. func displayMessageSent(_ message:String) {
  94. DispatchQueue.main.async {
  95. self.sentOutputField.stringValue = message
  96. }
  97. }
  98. func displayMessageReceived(_ message:String) {
  99. DispatchQueue.main.async {
  100. self.receivedOutputField.stringValue = message
  101. }
  102. }
  103. func prepareService(address: String, host: String) {
  104. if (service != nil) {
  105. return
  106. }
  107. if (TLSButton.intValue == 0) {
  108. service = EchoService(address:address)
  109. } else {
  110. let certificateURL = Bundle.main.url(forResource: "ssl",
  111. withExtension: "crt")!
  112. let certificates = try! String(contentsOf: certificateURL)
  113. service = EchoService(address:address, certificates:certificates, host:host)
  114. }
  115. if let service = service {
  116. service.channel.host = "example.com" // sample override
  117. }
  118. }
  119. func callServer(address:String, host:String) throws -> Void {
  120. prepareService(address:address, host:host)
  121. let requestMetadata = Metadata(["x-goog-api-key":"YOUR_API_KEY",
  122. "x-ios-bundle-identifier":Bundle.main.bundleIdentifier!])
  123. if (self.callSelectButton.selectedSegment == 0) {
  124. // NONSTREAMING
  125. if let service = service {
  126. let call = service.get()
  127. var requestMessage = Echo_EchoRequest()
  128. requestMessage.text = self.messageField.stringValue
  129. self.displayMessageSent(requestMessage.text)
  130. call.perform(request:requestMessage) {(callResult, response) in
  131. if let response = response {
  132. self.displayMessageReceived(response.text)
  133. } else {
  134. self.displayMessageReceived("No message received. gRPC Status \(callResult.statusCode): \(callResult.statusMessage)")
  135. }
  136. }
  137. }
  138. }
  139. else if (self.callSelectButton.selectedSegment == 1) {
  140. // STREAMING EXPAND
  141. if (!nowStreaming) {
  142. guard let service = service else {
  143. return
  144. }
  145. expandCall = service.expand()
  146. var requestMessage = Echo_EchoRequest()
  147. requestMessage.text = self.messageField.stringValue
  148. self.displayMessageSent(requestMessage.text)
  149. try expandCall!.perform(request:requestMessage) {(callResult, response) in
  150. }
  151. try! self.receiveExpandMessage()
  152. }
  153. }
  154. else if (self.callSelectButton.selectedSegment == 2) {
  155. // STREAMING COLLECT
  156. if (!nowStreaming) {
  157. guard let service = service else {
  158. return
  159. }
  160. collectCall = service.collect()
  161. try collectCall!.start(metadata:requestMetadata)
  162. try self.receiveCollectMessage()
  163. nowStreaming = true
  164. closeButton.isEnabled = true
  165. }
  166. self.sendCollectMessage()
  167. }
  168. else if (self.callSelectButton.selectedSegment == 3) {
  169. // STREAMING UPDATE
  170. if (!nowStreaming) {
  171. guard let service = service else {
  172. return
  173. }
  174. updateCall = service.update()
  175. try updateCall!.start(metadata:requestMetadata)
  176. try self.receiveUpdateMessage()
  177. nowStreaming = true
  178. closeButton.isEnabled = true
  179. }
  180. self.sendUpdateMessage()
  181. }
  182. }
  183. func receiveExpandMessage() throws -> Void {
  184. guard let expandCall = expandCall else {
  185. return
  186. }
  187. try expandCall.receiveMessage() {(responseMessage) in
  188. if let responseMessage = responseMessage {
  189. try self.receiveExpandMessage() // prepare to receive the next message
  190. self.displayMessageReceived(responseMessage.text)
  191. } else {
  192. print("expand closed")
  193. }
  194. }
  195. }
  196. func sendCollectMessage() {
  197. if let collectCall = collectCall {
  198. var requestMessage = Echo_EchoRequest()
  199. requestMessage.text = self.messageField.stringValue
  200. self.displayMessageSent(requestMessage.text)
  201. _ = collectCall.sendMessage(message:requestMessage)
  202. }
  203. }
  204. func receiveCollectMessage() throws -> Void {
  205. guard let collectCall = collectCall else {
  206. return
  207. }
  208. try collectCall.receiveMessage() {(responseMessage) in
  209. if let responseMessage = responseMessage {
  210. self.displayMessageReceived(responseMessage.text)
  211. } else {
  212. print("collect closed")
  213. self.nowStreaming = false
  214. self.closeButton.isEnabled = false
  215. }
  216. }
  217. }
  218. func sendUpdateMessage() {
  219. if let updateCall = updateCall {
  220. var requestMessage = Echo_EchoRequest()
  221. requestMessage.text = self.messageField.stringValue
  222. self.displayMessageSent(requestMessage.text)
  223. _ = updateCall.sendMessage(message:requestMessage)
  224. }
  225. }
  226. func receiveUpdateMessage() throws -> Void {
  227. guard let updateCall = updateCall else {
  228. return
  229. }
  230. try updateCall.receiveMessage() {(responseMessage) in
  231. try self.receiveUpdateMessage() // prepare to receive the next message
  232. if let responseMessage = responseMessage {
  233. DispatchQueue.main.async {
  234. self.receivedOutputField.stringValue = responseMessage.text
  235. }
  236. } else {
  237. print("update closed")
  238. self.nowStreaming = false
  239. self.closeButton.isEnabled = false
  240. }
  241. }
  242. }
  243. func sendClose() throws {
  244. if let updateCall = updateCall {
  245. try updateCall.close() {
  246. self.updateCall = nil
  247. self.nowStreaming = false
  248. self.closeButton.isEnabled = false
  249. }
  250. }
  251. if let collectCall = collectCall {
  252. try collectCall.close() {
  253. self.collectCall = nil
  254. self.nowStreaming = false
  255. self.closeButton.isEnabled = false
  256. }
  257. }
  258. }
  259. }