EchoServer.swift 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 Foundation
  34. import gRPC
  35. import Darwin // for sleep()
  36. // This seemed like a nice idea but doesn't work because
  37. // specific message types are in the protocol signatures.
  38. // There are also functions in the Session classes that depend
  39. // on specific message types.
  40. protocol UnaryServer {
  41. func handle(message:Echo_EchoRequest) -> Echo_EchoResponse?
  42. }
  43. protocol ServerStreamingServer {
  44. func handle(session:ServerStreamingSession, message:Echo_EchoRequest) -> Void
  45. }
  46. protocol ClientStreamingServer {
  47. func handle(session:ClientStreamingSession, message:Echo_EchoRequest) -> Void
  48. func close(session:ClientStreamingSession)
  49. }
  50. protocol BidiStreamingServer {
  51. func handle(session:BidiStreamingSession, message:Echo_EchoRequest) -> Void
  52. }
  53. // nonstreaming
  54. class UnarySession : Session {
  55. var handler : Handler
  56. var server : UnaryServer
  57. init(handler:Handler, server: UnaryServer) {
  58. self.handler = handler
  59. self.server = server
  60. }
  61. func run() {
  62. do {
  63. try handler.receiveMessage(initialMetadata:Metadata()) {(requestData) in
  64. if let requestData = requestData {
  65. let requestMessage = try! Echo_EchoRequest(protobuf:requestData)
  66. if let replyMessage = self.server.handle(message:requestMessage) { // calling stub
  67. try self.handler.sendResponse(message:replyMessage.serializeProtobuf(),
  68. statusCode: 0,
  69. statusMessage: "OK",
  70. trailingMetadata:Metadata())
  71. }
  72. }
  73. }
  74. } catch (let callError) {
  75. print("grpc error: \(callError)")
  76. }
  77. }
  78. }
  79. // server streaming
  80. class ServerStreamingSession : Session {
  81. var handler : Handler
  82. var server : ServerStreamingServer
  83. init(handler:Handler, server: ServerStreamingServer) {
  84. self.handler = handler
  85. self.server = server
  86. }
  87. func sendMessage(message:Echo_EchoResponse) -> Void {
  88. try! handler.sendResponse(message:message.serializeProtobuf()) {}
  89. }
  90. func run() {
  91. do {
  92. try handler.receiveMessage(initialMetadata:Metadata()) {(requestData) in
  93. if let requestData = requestData {
  94. let requestMessage = try! Echo_EchoRequest(protobuf:requestData)
  95. self.server.handle(session: self, message:requestMessage)
  96. }
  97. }
  98. } catch (let callError) {
  99. print("grpc error: \(callError)")
  100. }
  101. }
  102. }
  103. // client streaming
  104. class ClientStreamingSession : Session {
  105. var handler : Handler
  106. var server : ClientStreamingServer
  107. init(handler:Handler, server: ClientStreamingServer) {
  108. self.handler = handler
  109. self.server = server
  110. }
  111. func sendMessage(message:Echo_EchoResponse) -> Void {
  112. try! self.handler.sendResponse(message:message.serializeProtobuf(),
  113. statusCode: 0,
  114. statusMessage: "OK",
  115. trailingMetadata: Metadata())
  116. }
  117. func waitForMessage() {
  118. do {
  119. try handler.receiveMessage() {(requestData) in
  120. if let requestData = requestData {
  121. let requestMessage = try! Echo_EchoRequest(protobuf:requestData)
  122. self.waitForMessage()
  123. self.server.handle(session:self, message:requestMessage)
  124. } else {
  125. // if we get an empty message (requestData == nil), we close the connection
  126. self.server.close(session:self)
  127. }
  128. }
  129. } catch (let error) {
  130. print(error)
  131. }
  132. }
  133. func run() {
  134. do {
  135. try self.handler.sendMetadata(initialMetadata:Metadata()) {
  136. self.waitForMessage()
  137. }
  138. } catch (let callError) {
  139. print("grpc error: \(callError)")
  140. }
  141. }
  142. }
  143. // fully streaming
  144. class BidiStreamingSession : Session {
  145. var handler : Handler
  146. var server : BidiStreamingServer
  147. init(handler:Handler, server: BidiStreamingServer) {
  148. self.handler = handler
  149. self.server = server
  150. }
  151. func sendMessage(message:Echo_EchoResponse) -> Void {
  152. try! handler.sendResponse(message:message.serializeProtobuf()) {}
  153. }
  154. func waitForMessage() {
  155. do {
  156. try handler.receiveMessage() {(requestData) in
  157. if let requestData = requestData {
  158. let requestMessage = try! Echo_EchoRequest(protobuf:requestData)
  159. self.waitForMessage()
  160. self.server.handle(session:self, message:requestMessage)
  161. } else {
  162. // if we get an empty message (requestData == nil), we close the connection
  163. try self.handler.sendStatus(statusCode: 0,
  164. statusMessage: "OK",
  165. trailingMetadata: Metadata())
  166. {
  167. self.handler.shutdown()
  168. }
  169. }
  170. }
  171. } catch (let error) {
  172. print(error)
  173. }
  174. }
  175. func run() {
  176. do {
  177. try self.handler.sendMetadata(initialMetadata:Metadata()) {
  178. self.waitForMessage()
  179. }
  180. } catch (let callError) {
  181. print("grpc error: \(callError)")
  182. }
  183. }
  184. }
  185. class EchoServer {
  186. private var address: String
  187. private var server: Server
  188. init(address:String, secure:Bool) {
  189. gRPC.initialize()
  190. self.address = address
  191. if secure {
  192. let certificateURL = URL(fileURLWithPath:"ssl.crt")
  193. let certificate = try! String(contentsOf: certificateURL)
  194. let keyURL = URL(fileURLWithPath:"ssl.key")
  195. let key = try! String(contentsOf: keyURL)
  196. self.server = gRPC.Server(address:address, key:key, certs:certificate)
  197. } else {
  198. self.server = gRPC.Server(address:address)
  199. }
  200. }
  201. func start() {
  202. print("Server Starting")
  203. print("GRPC version " + gRPC.version())
  204. server.run {(handler) in
  205. print("Server received request to " + handler.host
  206. + " calling " + handler.method
  207. + " from " + handler.caller)
  208. if (handler.method == "/echo.Echo/Get") {
  209. handler.session = UnarySession(handler:handler,
  210. server:EchoGetServer())
  211. handler.session.run()
  212. }
  213. else if (handler.method == "/echo.Echo/Expand") {
  214. handler.session = ServerStreamingSession(handler:handler,
  215. server:EchoExpandServer())
  216. handler.session.run()
  217. }
  218. else if (handler.method == "/echo.Echo/Collect") {
  219. handler.session = ClientStreamingSession(handler:handler,
  220. server:EchoCollectServer())
  221. handler.session.run()
  222. }
  223. else if (handler.method == "/echo.Echo/Update") {
  224. handler.session = BidiStreamingSession(handler:handler,
  225. server:EchoUpdateServer())
  226. handler.session.run()
  227. }
  228. }
  229. }
  230. }
  231. // The following code is for developer/users to edit.
  232. // Everything above these lines is intended to be preexisting or generated.
  233. class EchoGetServer : UnaryServer {
  234. func handle(message:Echo_EchoRequest) -> Echo_EchoResponse? {
  235. var reply = Echo_EchoResponse()
  236. reply.text = "Swift echo get: " + message.text
  237. return reply
  238. }
  239. }
  240. class EchoExpandServer : ServerStreamingServer {
  241. func handle(session:ServerStreamingSession, message:Echo_EchoRequest) -> Void {
  242. let parts = message.text.components(separatedBy: " ")
  243. var i = 0
  244. for part in parts {
  245. var reply = Echo_EchoResponse()
  246. reply.text = "Swift echo expand (\(i)): \(part)"
  247. session.sendMessage(message:reply)
  248. i += 1
  249. sleep(1)
  250. }
  251. var reply = Echo_EchoResponse()
  252. session.sendMessage(message:reply)
  253. }
  254. }
  255. class EchoCollectServer : ClientStreamingServer {
  256. var result = ""
  257. func handle(session:ClientStreamingSession, message:Echo_EchoRequest) -> Void {
  258. if result != "" {
  259. result += " "
  260. }
  261. result += message.text
  262. }
  263. func close(session:ClientStreamingSession) {
  264. var reply = Echo_EchoResponse()
  265. reply.text = "Swift echo collect: " + result
  266. session.sendMessage(message:reply)
  267. }
  268. }
  269. class EchoUpdateServer : BidiStreamingServer {
  270. var i = 0
  271. func handle(session:BidiStreamingSession, message:Echo_EchoRequest) -> Void {
  272. var reply = Echo_EchoResponse()
  273. reply.text = "Swift echo update (\(i)): \(message.text)"
  274. session.sendMessage(message:reply)
  275. i += 1
  276. }
  277. }