SocketEngineSpec.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. //
  2. // SocketEngineSpec.swift
  3. // Socket.IO-Client-Swift
  4. //
  5. // Created by Erik Little on 10/7/15.
  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. //
  25. import Foundation
  26. import Starscream
  27. /// Specifies a SocketEngine.
  28. @objc public protocol SocketEngineSpec {
  29. // MARK: Properties
  30. /// The client for this engine.
  31. var client: SocketEngineClient? { get set }
  32. /// `true` if this engine is closed.
  33. var closed: Bool { get }
  34. /// If `true` the engine will attempt to use WebSocket compression.
  35. var compress: Bool { get }
  36. /// `true` if this engine is connected. Connected means that the initial poll connect has succeeded.
  37. var connected: Bool { get }
  38. /// The connect parameters sent during a connect.
  39. var connectParams: [String: Any]? { get set }
  40. /// An array of HTTPCookies that are sent during the connection.
  41. var cookies: [HTTPCookie]? { get }
  42. /// The queue that all engine actions take place on.
  43. var engineQueue: DispatchQueue { get }
  44. /// A dictionary of extra http headers that will be set during connection.
  45. var extraHeaders: [String: String]? { get set }
  46. /// When `true`, the engine is in the process of switching to WebSockets.
  47. var fastUpgrade: Bool { get }
  48. /// When `true`, the engine will only use HTTP long-polling as a transport.
  49. var forcePolling: Bool { get }
  50. /// When `true`, the engine will only use WebSockets as a transport.
  51. var forceWebsockets: Bool { get }
  52. /// If `true`, the engine is currently in HTTP long-polling mode.
  53. var polling: Bool { get }
  54. /// If `true`, the engine is currently seeing whether it can upgrade to WebSockets.
  55. var probing: Bool { get }
  56. /// The session id for this engine.
  57. var sid: String { get }
  58. /// The path to engine.io.
  59. var socketPath: String { get }
  60. /// The url for polling.
  61. var urlPolling: URL { get }
  62. /// The url for WebSockets.
  63. var urlWebSocket: URL { get }
  64. /// If `true`, then the engine is currently in WebSockets mode.
  65. @available(*, deprecated, message: "No longer needed, if we're not polling, then we must be doing websockets")
  66. var websocket: Bool { get }
  67. /// The WebSocket for this engine.
  68. var ws: WebSocket? { get }
  69. // MARK: Initializers
  70. /// Creates a new engine.
  71. ///
  72. /// - parameter client: The client for this engine.
  73. /// - parameter url: The url for this engine.
  74. /// - parameter options: The options for this engine.
  75. init(client: SocketEngineClient, url: URL, options: [String: Any]?)
  76. // MARK: Methods
  77. /// Starts the connection to the server.
  78. func connect()
  79. /// Called when an error happens during execution. Causes a disconnection.
  80. func didError(reason: String)
  81. /// Disconnects from the server.
  82. ///
  83. /// - parameter reason: The reason for the disconnection. This is communicated up to the client.
  84. func disconnect(reason: String)
  85. /// Called to switch from HTTP long-polling to WebSockets. After calling this method the engine will be in
  86. /// WebSocket mode.
  87. ///
  88. /// **You shouldn't call this directly**
  89. func doFastUpgrade()
  90. /// Causes any packets that were waiting for POSTing to be sent through the WebSocket. This happens because when
  91. /// the engine is attempting to upgrade to WebSocket it does not do any POSTing.
  92. ///
  93. /// **You shouldn't call this directly**
  94. func flushWaitingForPostToWebSocket()
  95. /// Parses raw binary received from engine.io.
  96. ///
  97. /// - parameter data: The data to parse.
  98. func parseEngineData(_ data: Data)
  99. /// Parses a raw engine.io packet.
  100. ///
  101. /// - parameter message: The message to parse.
  102. func parseEngineMessage(_ message: String)
  103. /// Writes a message to engine.io, independent of transport.
  104. ///
  105. /// - parameter msg: The message to send.
  106. /// - parameter type: The type of this message.
  107. /// - parameter data: Any data that this message has.
  108. /// - parameter completion: Callback called on transport write completion.
  109. func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data], completion: (() -> ())?)
  110. }
  111. extension SocketEngineSpec {
  112. var urlPollingWithSid: URL {
  113. var com = URLComponents(url: urlPolling, resolvingAgainstBaseURL: false)!
  114. com.percentEncodedQuery = com.percentEncodedQuery! + "&sid=\(sid.urlEncode()!)"
  115. return com.url!
  116. }
  117. var urlWebSocketWithSid: URL {
  118. var com = URLComponents(url: urlWebSocket, resolvingAgainstBaseURL: false)!
  119. com.percentEncodedQuery = com.percentEncodedQuery! + (sid == "" ? "" : "&sid=\(sid.urlEncode()!)")
  120. return com.url!
  121. }
  122. func addHeaders(to req: inout URLRequest, includingCookies additionalCookies: [HTTPCookie]? = nil) {
  123. var cookiesToAdd: [HTTPCookie] = cookies ?? []
  124. cookiesToAdd += additionalCookies ?? []
  125. if !cookiesToAdd.isEmpty {
  126. req.allHTTPHeaderFields = HTTPCookie.requestHeaderFields(with: cookiesToAdd)
  127. }
  128. if let extraHeaders = extraHeaders {
  129. for (headerName, value) in extraHeaders {
  130. req.setValue(value, forHTTPHeaderField: headerName)
  131. }
  132. }
  133. }
  134. func createBinaryDataForSend(using data: Data) -> Either<Data, String> {
  135. if polling {
  136. return .right("b4" + data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)))
  137. } else {
  138. return .left(Data([0x4]) + data)
  139. }
  140. }
  141. /// Send an engine message (4)
  142. func send(_ msg: String, withData datas: [Data], completion: (() -> ())? = nil) {
  143. write(msg, withType: .message, withData: datas, completion: completion)
  144. }
  145. }