SocketEnginePollable.swift 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. //
  2. // SocketEnginePollable.swift
  3. // Socket.IO-Client-Swift
  4. //
  5. // Created by Erik Little on 1/15/16.
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in
  15. // all copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. // THE SOFTWARE.
  24. import Foundation
  25. /// Protocol that is used to implement socket.io polling support
  26. public protocol SocketEnginePollable : SocketEngineSpec {
  27. // MARK: Properties
  28. /// `true` If engine's session has been invalidated.
  29. var invalidated: Bool { get }
  30. /// A queue of engine.io messages waiting for POSTing
  31. ///
  32. /// **You should not touch this directly**
  33. var postWait: [Post] { get set }
  34. /// The URLSession that will be used for polling.
  35. var session: URLSession? { get }
  36. /// `true` if there is an outstanding poll. Trying to poll before the first is done will cause socket.io to
  37. /// disconnect us.
  38. ///
  39. /// **Do not touch this directly**
  40. var waitingForPoll: Bool { get set }
  41. /// `true` if there is an outstanding post. Trying to post before the first is done will cause socket.io to
  42. /// disconnect us.
  43. ///
  44. /// **Do not touch this directly**
  45. var waitingForPost: Bool { get set }
  46. // MARK: Methods
  47. /// Call to send a long-polling request.
  48. ///
  49. /// You shouldn't need to call this directly, the engine should automatically maintain a long-poll request.
  50. func doPoll()
  51. /// Sends an engine.io message through the polling transport.
  52. ///
  53. /// You shouldn't call this directly, instead call the `write` method on `SocketEngine`.
  54. ///
  55. /// - parameter message: The message to send.
  56. /// - parameter withType: The type of message to send.
  57. /// - parameter withData: The data associated with this message.
  58. func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data], completion: (() -> ())?)
  59. /// Call to stop polling and invalidate the URLSession.
  60. func stopPolling()
  61. }
  62. // Default polling methods
  63. extension SocketEnginePollable {
  64. func createRequestForPostWithPostWait() -> URLRequest {
  65. defer {
  66. for packet in postWait { packet.completion?() }
  67. postWait.removeAll(keepingCapacity: true)
  68. }
  69. var postStr = ""
  70. for packet in postWait {
  71. postStr += "\(packet.msg.utf16.count):\(packet.msg)"
  72. }
  73. DefaultSocketLogger.Logger.log("Created POST string: \(postStr)", type: "SocketEnginePolling")
  74. var req = URLRequest(url: urlPollingWithSid)
  75. let postData = postStr.data(using: .utf8, allowLossyConversion: false)!
  76. addHeaders(to: &req)
  77. req.httpMethod = "POST"
  78. req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
  79. req.httpBody = postData
  80. req.setValue(String(postData.count), forHTTPHeaderField: "Content-Length")
  81. return req
  82. }
  83. /// Call to send a long-polling request.
  84. ///
  85. /// You shouldn't need to call this directly, the engine should automatically maintain a long-poll request.
  86. public func doPoll() {
  87. guard polling && !waitingForPoll && connected && !closed else { return }
  88. var req = URLRequest(url: urlPollingWithSid)
  89. addHeaders(to: &req)
  90. doLongPoll(for: req)
  91. }
  92. func doRequest(for req: URLRequest, callbackWith callback: @escaping (Data?, URLResponse?, Error?) -> ()) {
  93. guard polling && !closed && !invalidated && !fastUpgrade else { return }
  94. DefaultSocketLogger.Logger.log("Doing polling \(req.httpMethod ?? "") \(req)", type: "SocketEnginePolling")
  95. session?.dataTask(with: req, completionHandler: callback).resume()
  96. }
  97. func doLongPoll(for req: URLRequest) {
  98. waitingForPoll = true
  99. doRequest(for: req) {[weak self] data, res, err in
  100. guard let this = self, this.polling else { return }
  101. guard let data = data, let res = res as? HTTPURLResponse, res.statusCode == 200 else {
  102. if let err = err {
  103. DefaultSocketLogger.Logger.error(err.localizedDescription, type: "SocketEnginePolling")
  104. } else {
  105. DefaultSocketLogger.Logger.error("Error during long poll request", type: "SocketEnginePolling")
  106. }
  107. if this.polling {
  108. this.didError(reason: err?.localizedDescription ?? "Error")
  109. }
  110. return
  111. }
  112. DefaultSocketLogger.Logger.log("Got polling response", type: "SocketEnginePolling")
  113. if let str = String(data: data, encoding: .utf8) {
  114. this.parsePollingMessage(str)
  115. }
  116. this.waitingForPoll = false
  117. if this.fastUpgrade {
  118. this.doFastUpgrade()
  119. } else if !this.closed && this.polling {
  120. this.doPoll()
  121. }
  122. }
  123. }
  124. private func flushWaitingForPost() {
  125. guard postWait.count != 0 && connected else { return }
  126. guard polling else {
  127. flushWaitingForPostToWebSocket()
  128. return
  129. }
  130. let req = createRequestForPostWithPostWait()
  131. waitingForPost = true
  132. DefaultSocketLogger.Logger.log("POSTing", type: "SocketEnginePolling")
  133. doRequest(for: req) {[weak self] _, res, err in
  134. guard let this = self else { return }
  135. guard let res = res as? HTTPURLResponse, res.statusCode == 200 else {
  136. if let err = err {
  137. DefaultSocketLogger.Logger.error(err.localizedDescription, type: "SocketEnginePolling")
  138. } else {
  139. DefaultSocketLogger.Logger.error("Error flushing waiting posts", type: "SocketEnginePolling")
  140. }
  141. if this.polling {
  142. this.didError(reason: err?.localizedDescription ?? "Error")
  143. }
  144. return
  145. }
  146. this.waitingForPost = false
  147. if !this.fastUpgrade {
  148. this.flushWaitingForPost()
  149. this.doPoll()
  150. }
  151. }
  152. }
  153. func parsePollingMessage(_ str: String) {
  154. guard str.count != 1 else { return }
  155. DefaultSocketLogger.Logger.log("Got poll message: \(str)", type: "SocketEnginePolling")
  156. var reader = SocketStringReader(message: str)
  157. while reader.hasNext {
  158. if let n = Int(reader.readUntilOccurence(of: ":")) {
  159. parseEngineMessage(reader.read(count: n))
  160. } else {
  161. parseEngineMessage(str)
  162. break
  163. }
  164. }
  165. }
  166. /// Sends an engine.io message through the polling transport.
  167. ///
  168. /// You shouldn't call this directly, instead call the `write` method on `SocketEngine`.
  169. ///
  170. /// - parameter message: The message to send.
  171. /// - parameter withType: The type of message to send.
  172. /// - parameter withData: The data associated with this message.
  173. /// - parameter completion: Callback called on transport write completion.
  174. public func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data], completion: (() -> ())? = nil) {
  175. DefaultSocketLogger.Logger.log("Sending poll: \(message) as type: \(type.rawValue)", type: "SocketEnginePolling")
  176. postWait.append((String(type.rawValue) + message, completion))
  177. for data in datas {
  178. if case let .right(bin) = createBinaryDataForSend(using: data) {
  179. postWait.append((bin, {}))
  180. }
  181. }
  182. if !waitingForPost {
  183. flushWaitingForPost()
  184. }
  185. }
  186. /// Call to stop polling and invalidate the URLSession.
  187. public func stopPolling() {
  188. waitingForPoll = false
  189. waitingForPost = false
  190. session?.finishTasksAndInvalidate()
  191. }
  192. }