EchoViewController.swift 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 AppKit
  17. import SwiftGRPC
  18. class EchoViewController: NSViewController, NSTextFieldDelegate {
  19. @IBOutlet var messageField: NSTextField!
  20. @IBOutlet var sentOutputField: NSTextField!
  21. @IBOutlet var receivedOutputField: NSTextField!
  22. @IBOutlet var addressField: NSTextField!
  23. @IBOutlet var TLSButton: NSButton!
  24. @IBOutlet var callSelectButton: NSSegmentedControl!
  25. @IBOutlet var closeButton: NSButton!
  26. private var service: Echo_EchoServiceClient?
  27. private var expandCall: Echo_EchoExpandCall?
  28. private var collectCall: Echo_EchoCollectCall?
  29. private var updateCall: Echo_EchoUpdateCall?
  30. private var nowStreaming = false
  31. required init?(coder: NSCoder) {
  32. super.init(coder: coder)
  33. }
  34. private var enabled = false
  35. @IBAction func messageReturnPressed(sender _: NSTextField) {
  36. if enabled {
  37. do {
  38. try callServer(address: addressField.stringValue,
  39. host: "example.com")
  40. } catch {
  41. print(error)
  42. }
  43. }
  44. }
  45. @IBAction func addressReturnPressed(sender _: NSTextField) {
  46. if nowStreaming {
  47. do {
  48. try sendClose()
  49. } catch {
  50. print(error)
  51. }
  52. }
  53. // invalidate the service
  54. service = nil
  55. }
  56. @IBAction func buttonValueChanged(sender _: NSSegmentedControl) {
  57. if nowStreaming {
  58. do {
  59. try sendClose()
  60. } catch {
  61. print(error)
  62. }
  63. }
  64. }
  65. @IBAction func closeButtonPressed(sender _: NSButton) {
  66. if nowStreaming {
  67. do {
  68. try sendClose()
  69. } catch {
  70. print(error)
  71. }
  72. }
  73. }
  74. override func viewDidLoad() {
  75. closeButton.isEnabled = false
  76. // prevent the UI from trying to send messages until gRPC is initialized
  77. DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
  78. self.enabled = true
  79. }
  80. }
  81. func displayMessageSent(_ message: String) {
  82. DispatchQueue.main.async {
  83. self.sentOutputField.stringValue = message
  84. }
  85. }
  86. func displayMessageReceived(_ message: String) {
  87. DispatchQueue.main.async {
  88. self.receivedOutputField.stringValue = message
  89. }
  90. }
  91. func prepareService(address: String, host: String) {
  92. if service != nil {
  93. return
  94. }
  95. if TLSButton.intValue == 0 {
  96. service = Echo_EchoServiceClient(address: address, secure: false)
  97. } else {
  98. let certificateURL = Bundle.main.url(forResource: "ssl",
  99. withExtension: "crt")!
  100. let certificates = try! String(contentsOf: certificateURL)
  101. let arguments: [Channel.Argument] = [.sslTargetNameOverride(host)]
  102. service = Echo_EchoServiceClient(address: address, certificates: certificates, arguments: arguments)
  103. }
  104. if let service = service {
  105. service.host = "example.com" // sample override
  106. service.metadata = try! Metadata([
  107. "x-goog-api-key": "YOUR_API_KEY",
  108. "x-ios-bundle-identifier": Bundle.main.bundleIdentifier!
  109. ])
  110. }
  111. }
  112. func callServer(address: String, host: String) throws {
  113. prepareService(address: address, host: host)
  114. guard let service = service else {
  115. return
  116. }
  117. if callSelectButton.selectedSegment == 0 {
  118. // NONSTREAMING
  119. var requestMessage = Echo_EchoRequest()
  120. requestMessage.text = messageField.stringValue
  121. displayMessageSent(requestMessage.text)
  122. _ = try service.get(requestMessage) { responseMessage, callResult in
  123. if let responseMessage = responseMessage {
  124. self.displayMessageReceived(responseMessage.text)
  125. } else {
  126. self.displayMessageReceived("No message received. \(callResult)")
  127. }
  128. }
  129. } else if callSelectButton.selectedSegment == 1 {
  130. // STREAMING EXPAND
  131. if !nowStreaming {
  132. do {
  133. var requestMessage = Echo_EchoRequest()
  134. requestMessage.text = messageField.stringValue
  135. expandCall = try service.expand(requestMessage) { call in
  136. print("Completed expand \(call)")
  137. }
  138. try receiveExpandMessages()
  139. displayMessageSent(requestMessage.text)
  140. } catch {
  141. self.displayMessageReceived("No message received. \(error)")
  142. }
  143. }
  144. } else if callSelectButton.selectedSegment == 2 {
  145. // STREAMING COLLECT
  146. do {
  147. if !nowStreaming {
  148. let collectCall = try service.collect { call in
  149. print("Completed collect \(call)")
  150. }
  151. self.collectCall = collectCall
  152. nowStreaming = true
  153. DispatchQueue.main.async {
  154. self.closeButton.isEnabled = true
  155. }
  156. }
  157. try sendCollectMessage()
  158. } catch {
  159. self.displayMessageReceived("No message received. \(error)")
  160. }
  161. } else if callSelectButton.selectedSegment == 3 {
  162. // STREAMING UPDATE
  163. do {
  164. if !nowStreaming {
  165. let updateCall = try service.update { call in
  166. print("Completed update \(call)")
  167. }
  168. self.updateCall = updateCall
  169. nowStreaming = true
  170. try receiveUpdateMessages()
  171. DispatchQueue.main.async {
  172. self.closeButton.isEnabled = true
  173. }
  174. }
  175. try sendUpdateMessage()
  176. } catch {
  177. self.displayMessageReceived("No message received. \(error)")
  178. }
  179. }
  180. }
  181. func receiveExpandMessages() throws {
  182. guard let expandCall = expandCall else {
  183. return
  184. }
  185. try expandCall.receive { (response) in
  186. if case let result?? = response.result {
  187. self.displayMessageReceived(result.text)
  188. try! self.receiveExpandMessages()
  189. } else if let error = response.error {
  190. self.displayMessageReceived("No message received. \(error)")
  191. }
  192. }
  193. }
  194. func sendCollectMessage() throws {
  195. if let collectCall = collectCall {
  196. var requestMessage = Echo_EchoRequest()
  197. requestMessage.text = messageField.stringValue
  198. displayMessageSent(requestMessage.text)
  199. try collectCall.send(requestMessage) { (error) in
  200. if let error = error {
  201. print(error)
  202. }
  203. }
  204. }
  205. }
  206. func sendUpdateMessage() throws {
  207. if let updateCall = updateCall {
  208. var requestMessage = Echo_EchoRequest()
  209. requestMessage.text = messageField.stringValue
  210. displayMessageSent(requestMessage.text)
  211. try updateCall.send(requestMessage) { (error) in
  212. if let error = error {
  213. print(error)
  214. }
  215. }
  216. }
  217. }
  218. func receiveUpdateMessages() throws {
  219. guard let updateCall = updateCall else {
  220. return
  221. }
  222. try updateCall.receive { (response) in
  223. if case let result?? = response.result {
  224. self.displayMessageReceived(result.text)
  225. try! self.receiveUpdateMessages()
  226. } else if let error = response.error {
  227. self.displayMessageReceived("No message received. \(error)")
  228. }
  229. }
  230. }
  231. func sendClose() throws {
  232. if let updateCall = updateCall {
  233. try updateCall.closeSend {
  234. self.updateCall = nil
  235. self.nowStreaming = false
  236. DispatchQueue.main.async {
  237. self.closeButton.isEnabled = false
  238. }
  239. }
  240. }
  241. if let collectCall = collectCall {
  242. do {
  243. try collectCall.closeAndReceive { (response) in
  244. if let result = response.result {
  245. self.displayMessageReceived(result.text)
  246. } else if let error = response.error {
  247. self.displayMessageReceived("No message received. \(error)")
  248. }
  249. self.collectCall = nil
  250. self.nowStreaming = false
  251. DispatchQueue.main.async {
  252. self.closeButton.isEnabled = false
  253. }
  254. }
  255. }
  256. }
  257. }
  258. }