SocketEnginePollable.swift 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. var invalidated: Bool { get }
  28. /// Holds strings waiting to be sent over polling.
  29. /// You shouldn't need to mess with this.
  30. var postWait: [String] { get set }
  31. var session: NSURLSession? { get }
  32. /// Because socket.io doesn't let you send two polling request at the same time
  33. /// we have to keep track if there's an outstanding poll
  34. var waitingForPoll: Bool { get set }
  35. /// Because socket.io doesn't let you send two post request at the same time
  36. /// we have to keep track if there's an outstanding post
  37. var waitingForPost: Bool { get set }
  38. func doPoll()
  39. func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData])
  40. func stopPolling()
  41. }
  42. // Default polling methods
  43. extension SocketEnginePollable {
  44. private func addHeaders(req: NSMutableURLRequest) {
  45. if cookies != nil {
  46. let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
  47. req.allHTTPHeaderFields = headers
  48. }
  49. if extraHeaders != nil {
  50. for (headerName, value) in extraHeaders! {
  51. req.setValue(value, forHTTPHeaderField: headerName)
  52. }
  53. }
  54. }
  55. func createRequestForPostWithPostWait() -> NSURLRequest {
  56. var postStr = ""
  57. for packet in postWait {
  58. let len = packet.characters.count
  59. postStr += "\(len):\(packet)"
  60. }
  61. DefaultSocketLogger.Logger.log("Created POST string: %@", type: "SocketEnginePolling", args: postStr)
  62. postWait.removeAll(keepCapacity: false)
  63. let req = NSMutableURLRequest(URL: urlPollingWithSid)
  64. addHeaders(req)
  65. req.HTTPMethod = "POST"
  66. req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
  67. let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
  68. allowLossyConversion: false)!
  69. req.HTTPBody = postData
  70. req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
  71. return req
  72. }
  73. public func doPoll() {
  74. if websocket || waitingForPoll || !connected || closed {
  75. return
  76. }
  77. waitingForPoll = true
  78. let req = NSMutableURLRequest(URL: urlPollingWithSid)
  79. addHeaders(req)
  80. doLongPoll(req)
  81. }
  82. func doRequest(req: NSURLRequest, withCallback callback: (NSData?, NSURLResponse?, NSError?) -> Void) {
  83. if !polling || closed || invalidated || fastUpgrade {
  84. DefaultSocketLogger.Logger.error("Tried to do polling request when not supposed to", type: "SocketEnginePolling")
  85. return
  86. }
  87. DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling")
  88. session?.dataTaskWithRequest(req, completionHandler: callback).resume()
  89. }
  90. func doLongPoll(req: NSURLRequest) {
  91. doRequest(req) {[weak self] data, res, err in
  92. guard let this = self where this.polling else { return }
  93. if err != nil || data == nil {
  94. DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
  95. if this.polling {
  96. this.didError(err?.localizedDescription ?? "Error")
  97. }
  98. return
  99. }
  100. DefaultSocketLogger.Logger.log("Got polling response", type: "SocketEnginePolling")
  101. if let str = String(data: data!, encoding: NSUTF8StringEncoding) {
  102. dispatch_async(this.parseQueue) {
  103. this.parsePollingMessage(str)
  104. }
  105. }
  106. this.waitingForPoll = false
  107. if this.fastUpgrade {
  108. this.doFastUpgrade()
  109. } else if !this.closed && this.polling {
  110. this.doPoll()
  111. }
  112. }
  113. }
  114. private func flushWaitingForPost() {
  115. if postWait.count == 0 || !connected {
  116. return
  117. } else if websocket {
  118. flushWaitingForPostToWebSocket()
  119. return
  120. }
  121. let req = createRequestForPostWithPostWait()
  122. waitingForPost = true
  123. DefaultSocketLogger.Logger.log("POSTing", type: "SocketEnginePolling")
  124. doRequest(req) {[weak self] data, res, err in
  125. guard let this = self else { return }
  126. if err != nil {
  127. DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
  128. if this.polling {
  129. this.didError(err?.localizedDescription ?? "Error")
  130. }
  131. return
  132. }
  133. this.waitingForPost = false
  134. dispatch_async(this.emitQueue) {
  135. if !this.fastUpgrade {
  136. this.flushWaitingForPost()
  137. this.doPoll()
  138. }
  139. }
  140. }
  141. }
  142. func parsePollingMessage(str: String) {
  143. guard str.characters.count != 1 else { return }
  144. var reader = SocketStringReader(message: str)
  145. while reader.hasNext {
  146. if let n = Int(reader.readUntilStringOccurence(":")) {
  147. let str = reader.read(n)
  148. dispatch_async(handleQueue) {
  149. self.parseEngineMessage(str, fromPolling: true)
  150. }
  151. } else {
  152. dispatch_async(handleQueue) {
  153. self.parseEngineMessage(str, fromPolling: true)
  154. }
  155. break
  156. }
  157. }
  158. }
  159. /// Send polling message.
  160. /// Only call on emitQueue
  161. public func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData]) {
  162. DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue)
  163. let fixedMessage: String
  164. if doubleEncodeUTF8 {
  165. fixedMessage = doubleEncodeUTF8(message)
  166. } else {
  167. fixedMessage = message
  168. }
  169. let strMsg = "\(type.rawValue)\(fixedMessage)"
  170. postWait.append(strMsg)
  171. for data in datas {
  172. if case let .Right(bin) = createBinaryDataForSend(data) {
  173. postWait.append(bin)
  174. }
  175. }
  176. if !waitingForPost {
  177. flushWaitingForPost()
  178. }
  179. }
  180. public func stopPolling() {
  181. waitingForPoll = false
  182. waitingForPost = false
  183. session?.finishTasksAndInvalidate()
  184. }
  185. }