You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

308 lines
9.7 KiB

2 years ago
  1. ![starscream](https://raw.githubusercontent.com/daltoniam/starscream/assets/starscream.jpg)
  2. Starscream is a conforming WebSocket ([RFC 6455](http://tools.ietf.org/html/rfc6455)) library in Swift.
  3. ## Features
  4. - Conforms to all of the base [Autobahn test suite](https://crossbar.io/autobahn/).
  5. - Nonblocking. Everything happens in the background, thanks to GCD.
  6. - TLS/WSS support.
  7. - Compression Extensions support ([RFC 7692](https://tools.ietf.org/html/rfc7692))
  8. ### Import the framework
  9. First thing is to import the framework. See the Installation instructions on how to add the framework to your project.
  10. ```swift
  11. import Starscream
  12. ```
  13. ### Connect to the WebSocket Server
  14. Once imported, you can open a connection to your WebSocket server. Note that `socket` is probably best as a property, so it doesn't get deallocated right after being setup.
  15. ```swift
  16. var request = URLRequest(url: URL(string: "http://localhost:8080")!)
  17. request.timeoutInterval = 5
  18. socket = WebSocket(request: request)
  19. socket.delegate = self
  20. socket.connect()
  21. ```
  22. After you are connected, there is either a delegate or closure you can use for process WebSocket events.
  23. ### Receiving data from a WebSocket
  24. `didReceive` receives all the WebSocket events in a single easy to handle enum.
  25. ```swift
  26. func didReceive(event: WebSocketEvent, client: WebSocket) {
  27. switch event {
  28. case .connected(let headers):
  29. isConnected = true
  30. print("websocket is connected: \(headers)")
  31. case .disconnected(let reason, let code):
  32. isConnected = false
  33. print("websocket is disconnected: \(reason) with code: \(code)")
  34. case .text(let string):
  35. print("Received text: \(string)")
  36. case .binary(let data):
  37. print("Received data: \(data.count)")
  38. case .ping(_):
  39. break
  40. case .pong(_):
  41. break
  42. case .viabilityChanged(_):
  43. break
  44. case .reconnectSuggested(_):
  45. break
  46. case .cancelled:
  47. isConnected = false
  48. case .error(let error):
  49. isConnected = false
  50. handleError(error)
  51. }
  52. }
  53. ```
  54. The closure of this would be:
  55. ```swift
  56. socket.onEvent = { event in
  57. switch event {
  58. // handle events just like above...
  59. }
  60. }
  61. ```
  62. ### Writing to a WebSocket
  63. ### write a binary frame
  64. The writeData method gives you a simple way to send `Data` (binary) data to the server.
  65. ```swift
  66. socket.write(data: data) //write some Data over the socket!
  67. ```
  68. ### write a string frame
  69. The writeString method is the same as writeData, but sends text/string.
  70. ```swift
  71. socket.write(string: "Hi Server!") //example on how to write text over the socket!
  72. ```
  73. ### write a ping frame
  74. The writePing method is the same as write, but sends a ping control frame.
  75. ```swift
  76. socket.write(ping: Data()) //example on how to write a ping control frame over the socket!
  77. ```
  78. ### write a pong frame
  79. the writePong method is the same as writePing, but sends a pong control frame.
  80. ```swift
  81. socket.write(pong: Data()) //example on how to write a pong control frame over the socket!
  82. ```
  83. Starscream will automatically respond to incoming `ping` control frames so you do not need to manually send `pong`s.
  84. However if for some reason you need to control this process you can turn off the automatic `ping` response by disabling `respondToPingWithPong`.
  85. ```swift
  86. socket.respondToPingWithPong = false //Do not automaticaly respond to incoming pings with pongs.
  87. ```
  88. In most cases you will not need to do this.
  89. ### disconnect
  90. The disconnect method does what you would expect and closes the socket.
  91. ```swift
  92. socket.disconnect()
  93. ```
  94. The disconnect method can also send a custom close code if desired.
  95. ```swift
  96. socket.disconnect(closeCode: CloseCode.normal.rawValue)
  97. ```
  98. ### Custom Headers, Protocols and Timeout
  99. You can override the default websocket headers, add your own custom ones and set a timeout:
  100. ```swift
  101. var request = URLRequest(url: URL(string: "ws://localhost:8080/")!)
  102. request.timeoutInterval = 5 // Sets the timeout for the connection
  103. request.setValue("someother protocols", forHTTPHeaderField: "Sec-WebSocket-Protocol")
  104. request.setValue("14", forHTTPHeaderField: "Sec-WebSocket-Version")
  105. request.setValue("chat,superchat", forHTTPHeaderField: "Sec-WebSocket-Protocol")
  106. request.setValue("Everything is Awesome!", forHTTPHeaderField: "My-Awesome-Header")
  107. let socket = WebSocket(request: request)
  108. ```
  109. ### SSL Pinning
  110. SSL Pinning is also supported in Starscream.
  111. Allow Self-signed certificates:
  112. ```swift
  113. var request = URLRequest(url: URL(string: "ws://localhost:8080/")!)
  114. let pinner = FoundationSecurity(allowSelfSigned: true) // don't validate SSL certificates
  115. let socket = WebSocket(request: request, certPinner: pinner)
  116. ```
  117. TODO: Update docs on how to load certificates and public keys into an app bundle, use the builtin pinner and TrustKit.
  118. ### Compression Extensions
  119. Compression Extensions ([RFC 7692](https://tools.ietf.org/html/rfc7692)) is supported in Starscream. Compression is enabled by default, however compression will only be used if it is supported by the server as well. You may enable or disable compression via the `.enableCompression` property:
  120. ```swift
  121. var request = URLRequest(url: URL(string: "ws://localhost:8080/")!)
  122. let compression = WSCompression()
  123. let socket = WebSocket(request: request, compressionHandler: compression)
  124. ```
  125. Compression should be disabled if your application is transmitting already-compressed, random, or other uncompressable data.
  126. ### Custom Queue
  127. A custom queue can be specified when delegate methods are called. By default `DispatchQueue.main` is used, thus making all delegate methods calls run on the main thread. It is important to note that all WebSocket processing is done on a background thread, only the delegate method calls are changed when modifying the queue. The actual processing is always on a background thread and will not pause your app.
  128. ```swift
  129. socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"])
  130. //create a custom queue
  131. socket.callbackQueue = DispatchQueue(label: "com.vluxe.starscream.myapp")
  132. ```
  133. ## Example Project
  134. Check out the SimpleTest project in the examples directory to see how to setup a simple connection to a WebSocket server.
  135. ## Requirements
  136. Starscream works with iOS 8/10.10 or above for CocoaPods/framework support. To use Starscream with a project targeting iOS 7, you must include all Swift files directly in your project.
  137. ## Installation
  138. ### CocoaPods
  139. Check out [Get Started](http://cocoapods.org/) tab on [cocoapods.org](http://cocoapods.org/).
  140. To use Starscream in your project add the following 'Podfile' to your project
  141. source 'https://github.com/CocoaPods/Specs.git'
  142. platform :ios, '9.0'
  143. use_frameworks!
  144. pod 'Starscream', '~> 4.0.0'
  145. Then run:
  146. pod install
  147. ### Carthage
  148. Check out the [Carthage](https://github.com/Carthage/Carthage) docs on how to add a install. The `Starscream` framework is already setup with shared schemes.
  149. [Carthage Install](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application)
  150. You can install Carthage with [Homebrew](http://brew.sh/) using the following command:
  151. ```bash
  152. $ brew update
  153. $ brew install carthage
  154. ```
  155. To integrate Starscream into your Xcode project using Carthage, specify it in your `Cartfile`:
  156. ```
  157. github "daltoniam/Starscream" >= 4.0.0
  158. ```
  159. ### Accio
  160. Check out the [Accio](https://github.com/JamitLabs/Accio) docs on how to add a install.
  161. Add the following to your Package.swift:
  162. ```swift
  163. .package(url: "https://github.com/daltoniam/Starscream.git", .upToNextMajor(from: "4.0.0")),
  164. ```
  165. Next, add `Starscream` to your App targets dependencies like so:
  166. ```swift
  167. .target(
  168. name: "App",
  169. dependencies: [
  170. "Starscream",
  171. ]
  172. ),
  173. ```
  174. Then run `accio update`.
  175. ### Rogue
  176. First see the [installation docs](https://github.com/acmacalister/Rogue) for how to install Rogue.
  177. To install Starscream run the command below in the directory you created the rogue file.
  178. ```
  179. rogue add https://github.com/daltoniam/Starscream
  180. ```
  181. Next open the `libs` folder and add the `Starscream.xcodeproj` to your Xcode project. Once that is complete, in your "Build Phases" add the `Starscream.framework` to your "Link Binary with Libraries" phase. Make sure to add the `libs` folder to your `.gitignore` file.
  182. ### Swift Package Manager
  183. The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler.
  184. Once you have your Swift package set up, adding Starscream as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`.
  185. ```swift
  186. dependencies: [
  187. .Package(url: "https://github.com/daltoniam/Starscream.git", majorVersion: 4)
  188. ]
  189. ```
  190. ### Other
  191. Simply grab the framework (either via git submodule or another package manager).
  192. Add the `Starscream.xcodeproj` to your Xcode project. Once that is complete, in your "Build Phases" add the `Starscream.framework` to your "Link Binary with Libraries" phase.
  193. ### Add Copy Frameworks Phase
  194. If you are running this in an OSX app or on a physical iOS device you will need to make sure you add the `Starscream.framework` to be included in your app bundle. To do this, in Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar. In the tab bar at the top of that window, open the "Build Phases" panel. Expand the "Link Binary with Libraries" group, and add `Starscream.framework`. Click on the + button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add `Starscream.framework` respectively.
  195. ## TODOs
  196. - [ ] Proxy support
  197. ## License
  198. Starscream is licensed under the Apache v2 License.
  199. ## Contact
  200. ### Dalton Cherry
  201. * https://github.com/daltoniam
  202. * http://twitter.com/daltoniam
  203. * http://daltoniam.com
  204. ### Austin Cherry ###
  205. * https://github.com/acmacalister
  206. * http://twitter.com/acmacalister
  207. * http://austincherry.me