Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05c0874f32 | ||
|
|
2e5442d386 | ||
|
|
f9ae0cfdb3 | ||
|
|
7ad90de184 | ||
|
|
4383ddfe65 | ||
|
|
45373ad680 | ||
|
|
5ced8a5a9e | ||
|
|
6fd3294fba | ||
|
|
bfa163f3c2 | ||
|
|
d8826a9db3 | ||
|
|
b9e3de2d50 | ||
|
|
e163598ee6 | ||
|
|
2c059e1a6e | ||
|
|
6f21059ff8 | ||
|
|
58a5a17464 | ||
|
|
cb0a6f5460 | ||
|
|
b919d3e411 | ||
|
|
02f30a81dd | ||
|
|
e57bcba47d | ||
|
|
71f9058723 | ||
|
|
0564ded492 | ||
|
|
ff48d3a186 | ||
|
|
4fa3225cba | ||
|
|
ee24943c72 | ||
|
|
31e4c60db8 | ||
|
|
ab536e2279 | ||
|
|
3d47ff469f | ||
|
|
3401414430 | ||
|
|
50216647ca | ||
|
|
98063c8bf7 | ||
|
|
9747cc4ddc | ||
|
|
7e23597351 | ||
|
|
437c0880e8 | ||
|
|
c237197b8c | ||
|
|
4ea3f40ca7 | ||
|
|
a24b54c18f | ||
|
|
2377c8b45f | ||
|
|
e02ca23d14 | ||
|
|
18285f5401 | ||
|
|
1c80cc7e4c | ||
|
|
0959dd35d7 | ||
|
|
5d23270d70 | ||
|
|
2b4b5bf407 | ||
|
|
84cb635f11 | ||
|
|
119b479be2 | ||
|
|
9ff90f511e | ||
|
|
82e7882497 | ||
|
|
8e1434e63b | ||
|
|
44ee94d2ac | ||
|
|
6efeb7d5b2 | ||
|
|
e1865e3f94 | ||
|
|
1b4b571be6 | ||
|
|
c9f653ef2c | ||
|
|
3073130598 | ||
|
|
ed3d49001f | ||
|
|
4ee196c5fb | ||
|
|
baca9fc8da | ||
|
|
1a5ac74984 | ||
|
|
6c779e84d2 | ||
|
|
293d71bf97 | ||
|
|
2f1f77141e | ||
|
|
d4c01183ab | ||
|
|
5d81377e0a | ||
|
|
8f8d5acdba | ||
|
|
a0167ae213 | ||
|
|
4f5837afa7 | ||
|
|
718caba9d9 | ||
|
|
2919d4a5ce | ||
|
|
a53b7167b6 | ||
|
|
6c6b4f32c9 | ||
|
|
3a842469ec | ||
|
|
596a499041 | ||
|
|
76a572e735 | ||
|
|
6da9463c8d | ||
|
|
2f7a5405b0 | ||
|
|
62131ef904 | ||
|
|
5976ef1752 | ||
|
|
16e0bf6319 | ||
|
|
11c0ac249b | ||
|
|
1e96d7982d | ||
|
|
2f4c942dcf | ||
|
|
70283acc1f | ||
|
|
e16914f7d6 | ||
|
|
c795f9fb25 | ||
|
|
12f9207d8a | ||
|
|
0bf27b8c49 | ||
|
|
6ac96f8d91 | ||
|
|
f7397155b6 | ||
|
|
70d59ea9d4 | ||
|
|
7fe2dc2c70 | ||
|
|
fe9ee602e7 | ||
|
|
6fa5ce9168 | ||
|
|
43b2d4646f | ||
|
|
0f70079382 | ||
|
|
750ba138e1 | ||
|
|
3e8ca90e3a | ||
|
|
2a25027077 | ||
|
|
15dfba42a7 | ||
|
|
76ef3596f0 | ||
|
|
8e208b1c66 | ||
|
|
8c9a93f79d | ||
|
|
cf651b8a00 | ||
|
|
b8307b6b27 | ||
|
|
fe3599d1fe | ||
|
|
8d22de967e | ||
|
|
ff9c1bb67b | ||
|
|
c92e146dfc | ||
|
|
d71f81745e | ||
|
|
228c0c7c9b | ||
|
|
d36ef10404 | ||
|
|
c5c00510e5 | ||
|
|
e38c4081ec | ||
|
|
5060f90a79 | ||
|
|
57670ec613 | ||
|
|
3f57c7e0a9 | ||
|
|
efe0d01592 | ||
|
|
f9c665a542 | ||
|
|
b67b6abbdf | ||
|
|
d912796fa5 | ||
|
|
c9ac69f408 | ||
|
|
cc7d96e3d5 | ||
|
|
bf1104443a | ||
|
|
adf8692234 | ||
|
|
94f02e567a | ||
|
|
4eca685dc2 |
No files matched your search
+1
-1
@@ -1,7 +1,7 @@
|
||||
language: objective-c
|
||||
xcode_project: Socket.IO-Client-Swift.xcodeproj # path to your xcodeproj folder
|
||||
xcode_scheme: SocketIO-iOS
|
||||
osx_image: xcode7
|
||||
osx_image: xcode7.3
|
||||
before_install:
|
||||
- cd Socket.IO-Test-Server/
|
||||
- npm install
|
||||
|
||||
@@ -5,7 +5,7 @@ Socket.IO-client for iOS/OS X.
|
||||
|
||||
##Example
|
||||
```swift
|
||||
let socket = SocketIOClient(socketURL: "localhost:8080", options: [.Log(true), .ForcePolling(true)])
|
||||
let socket = SocketIOClient(socketURL: NSURL(string: "http://localhost:8080")!, options: [.Log(true), .ForcePolling(true)])
|
||||
|
||||
socket.on("connect") {data, ack in
|
||||
print("socket connected")
|
||||
@@ -26,7 +26,8 @@ socket.connect()
|
||||
|
||||
##Objective-C Example
|
||||
```objective-c
|
||||
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" options:@{@"log": @YES, @"forcePolling": @YES}];
|
||||
NSURL* url = [[NSURL alloc] initWithString:@"http://localhost:8080"];
|
||||
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:url options:@{@"log": @YES, @"forcePolling": @YES}];
|
||||
|
||||
[socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
|
||||
NSLog(@"socket connected");
|
||||
@@ -54,7 +55,9 @@ SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8
|
||||
- Can be used from Objective-C
|
||||
|
||||
##Installation
|
||||
Requires Swift 2/Xcode 7
|
||||
Requires Swift 2.2/Xcode 7.3
|
||||
|
||||
If you need Swift 2.1/Xcode 7.2 use v5.5.0 (Pre-Swift 2.2 support is no longer maintained)
|
||||
|
||||
If you need Swift 1.2/Xcode 6.3/4 use v2.4.5 (Pre-Swift 2 support is no longer maintained)
|
||||
|
||||
@@ -74,7 +77,7 @@ import PackageDescription
|
||||
let package = Package(
|
||||
name: "YourSocketIOProject",
|
||||
dependencies: [
|
||||
.Package(url: "https://github.com/socketio/socket.io-client-swift", majorVersion: 5)
|
||||
.Package(url: "https://github.com/socketio/socket.io-client-swift", majorVersion: 6)
|
||||
]
|
||||
)
|
||||
```
|
||||
@@ -85,7 +88,7 @@ Carthage
|
||||
-----------------
|
||||
Add this line to your `Cartfile`:
|
||||
```
|
||||
github "socketio/socket.io-client-swift" ~> 5.2.2 # Or latest version
|
||||
github "socketio/socket.io-client-swift" ~> 6.1.4 # Or latest version
|
||||
```
|
||||
|
||||
Run `carthage update --platform ios,macosx`.
|
||||
@@ -99,7 +102,7 @@ source 'https://github.com/CocoaPods/Specs.git'
|
||||
platform :ios, '8.0'
|
||||
use_frameworks!
|
||||
|
||||
pod 'Socket.IO-Client-Swift', '~> 5.2.2' # Or latest version
|
||||
pod 'Socket.IO-Client-Swift', '~> 6.1.4' # Or latest version
|
||||
```
|
||||
|
||||
Install pods:
|
||||
@@ -127,7 +130,7 @@ CocoaSeeds
|
||||
Add this line to your `Seedfile`:
|
||||
|
||||
```
|
||||
github "socketio/socket.io-client-swift", "v5.2.2", :files => "Source/*.swift" # Or latest version
|
||||
github "socketio/socket.io-client-swift", "v6.1.4", :files => "Source/*.swift" # Or latest version
|
||||
```
|
||||
|
||||
Run `seed install`.
|
||||
@@ -136,9 +139,9 @@ Run `seed install`.
|
||||
##API
|
||||
Constructors
|
||||
-----------
|
||||
`init(var socketURL: String, options: Set<SocketIOClientOption> = [])` - Creates a new SocketIOClient. opts is a Set of SocketIOClientOption. If your socket.io server is secure, you need to specify `https` in your socketURL.
|
||||
`init(var socketURL: NSURL, options: Set<SocketIOClientOption> = [])` - Creates a new SocketIOClient. options is a Set of SocketIOClientOption. If your socket.io server is secure, you need to specify `https` in your socketURL.
|
||||
|
||||
`convenience init(socketURL: String, options: NSDictionary?)` - Same as above, but meant for Objective-C. See Options on how convert between SocketIOClientOptions and dictionary keys.
|
||||
`convenience init(socketURL: NSURL, options: NSDictionary?)` - Same as above, but meant for Objective-C. See Options on how convert between SocketIOClientOptions and dictionary keys.
|
||||
|
||||
Options
|
||||
-------
|
||||
@@ -146,24 +149,25 @@ All options are a case of SocketIOClientOption. To get the Objective-C Option, c
|
||||
|
||||
```swift
|
||||
case ConnectParams([String: AnyObject]) // Dictionary whose contents will be passed with the connection.
|
||||
case Reconnects(Bool) // Whether to reconnect on server lose. Default is `true`
|
||||
case ReconnectAttempts(Int) // How many times to reconnect. Default is `-1` (infinite tries)
|
||||
case ReconnectWait(Int) // Amount of time to wait between reconnects. Default is `10`
|
||||
case Cookies([NSHTTPCookie]) // An array of NSHTTPCookies. Passed during the handshake. Default is nil.
|
||||
case DoubleEncodeUTF8(Bool) // Whether or not to double encode utf8. If using the node based server this should be true. Default is true.
|
||||
case ExtraHeaders([String: String]) // Adds custom headers to the initial request. Default is nil.
|
||||
case ForcePolling(Bool) // `true` forces the client to use xhr-polling. Default is `false`
|
||||
case ForceNew(Bool) // Will a create a new engine for each connect. Useful if you find a bug in the engine related to reconnects
|
||||
case ForceWebsockets(Bool) // `true` forces the client to use WebSockets. Default is `false`
|
||||
case Nsp(String) // The namespace to connect to. Must begin with /. Default is `/`
|
||||
case Cookies([NSHTTPCookie]) // An array of NSHTTPCookies. Passed during the handshake. Default is nil.
|
||||
case HandleQueue(dispatch_queue_t) // The dispatch queue that handlers are run on. Default is the main queue.
|
||||
case Log(Bool) // If `true` socket will log debug messages. Default is false.
|
||||
case Logger(SocketLogger) // Custom logger that conforms to SocketLogger. Will use the default logging otherwise.
|
||||
case Nsp(String) // The namespace to connect to. Must begin with /. Default is `/`
|
||||
case Path(String) // If the server uses a custom path. ex: `"/swift/"`. Default is `""`
|
||||
case Reconnects(Bool) // Whether to reconnect on server lose. Default is `true`
|
||||
case ReconnectAttempts(Int) // How many times to reconnect. Default is `-1` (infinite tries)
|
||||
case ReconnectWait(Int) // Amount of time to wait between reconnects. Default is `10`
|
||||
case SessionDelegate(NSURLSessionDelegate) // Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
|
||||
case Path(String) // If the server uses a custom path. ex: `"/swift"`. Default is `""`
|
||||
case ExtraHeaders([String: String]) // Adds custom headers to the initial request. Default is nil.
|
||||
case HandleQueue(dispatch_queue_t) // The dispatch queue that handlers are run on. Default is the main queue.
|
||||
case VoipEnabled(Bool) // Only use this option if you're using the client with VoIP services. Changes the way the WebSocket is created. Default is false
|
||||
case Secure(Bool) // If the connection should use TLS. Default is false.
|
||||
case Security(SSLSecurity) // Allows you to set which certs are valid. Useful for SSL pinning.
|
||||
case SelfSigned(Bool) // Sets WebSocket.selfSignedSSL (Don't do this, iOS will yell at you)
|
||||
|
||||
case VoipEnabled(Bool) // Only use this option if you're using the client with VoIP services. Changes the way the WebSocket is created. Default is false
|
||||
```
|
||||
Methods
|
||||
-------
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "Socket.IO-Client-Swift"
|
||||
s.module_name = "SocketIOClientSwift"
|
||||
s.version = "5.2.2"
|
||||
s.version = "6.1.4"
|
||||
s.summary = "Socket.IO-client for iOS and OS X"
|
||||
s.description = <<-DESC
|
||||
Socket.IO-client for iOS and OS X.
|
||||
@@ -14,7 +14,7 @@ Pod::Spec.new do |s|
|
||||
s.ios.deployment_target = '8.0'
|
||||
s.osx.deployment_target = '10.10'
|
||||
s.tvos.deployment_target = '9.0'
|
||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v5.2.2' }
|
||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v6.1.4' }
|
||||
s.source_files = "Source/**/*.swift"
|
||||
s.requires_arc = true
|
||||
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
|
||||
|
||||
@@ -60,11 +60,6 @@
|
||||
74171E8F1C10CD240062D398 /* SocketEventHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E571C10CD240062D398 /* SocketEventHandler.swift */; };
|
||||
74171E911C10CD240062D398 /* SocketEventHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E571C10CD240062D398 /* SocketEventHandler.swift */; };
|
||||
74171E921C10CD240062D398 /* SocketEventHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E571C10CD240062D398 /* SocketEventHandler.swift */; };
|
||||
74171E931C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
|
||||
74171E941C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
|
||||
74171E951C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
|
||||
74171E971C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
|
||||
74171E981C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
|
||||
74171E991C10CD240062D398 /* SocketIOClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E591C10CD240062D398 /* SocketIOClient.swift */; };
|
||||
74171E9A1C10CD240062D398 /* SocketIOClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E591C10CD240062D398 /* SocketIOClient.swift */; };
|
||||
74171E9B1C10CD240062D398 /* SocketIOClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E591C10CD240062D398 /* SocketIOClient.swift */; };
|
||||
@@ -106,32 +101,38 @@
|
||||
74171EC51C10CD240062D398 /* SocketTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E601C10CD240062D398 /* SocketTypes.swift */; };
|
||||
74171EC71C10CD240062D398 /* SocketTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E601C10CD240062D398 /* SocketTypes.swift */; };
|
||||
74171EC81C10CD240062D398 /* SocketTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E601C10CD240062D398 /* SocketTypes.swift */; };
|
||||
74171EC91C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; };
|
||||
74171ECA1C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; };
|
||||
74171ECB1C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; };
|
||||
74171ECD1C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; };
|
||||
74171ECE1C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; };
|
||||
74171ECF1C10CD240062D398 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E621C10CD240062D398 /* WebSocket.swift */; };
|
||||
74171ED01C10CD240062D398 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E621C10CD240062D398 /* WebSocket.swift */; };
|
||||
74171ED11C10CD240062D398 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E621C10CD240062D398 /* WebSocket.swift */; };
|
||||
74171ED31C10CD240062D398 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E621C10CD240062D398 /* WebSocket.swift */; };
|
||||
74171ED41C10CD240062D398 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E621C10CD240062D398 /* WebSocket.swift */; };
|
||||
741F39EE1BD025D80026C9CC /* SocketEngineTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */; };
|
||||
741F39EF1BD025D80026C9CC /* SocketEngineTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */; };
|
||||
7420CB791C49629E00956AA4 /* SocketEnginePollable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */; };
|
||||
7420CB7A1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */; };
|
||||
7420CB7B1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */; };
|
||||
742D150C1CA5794B00BD987D /* SocketObjectiveCTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 742D150B1CA5794B00BD987D /* SocketObjectiveCTest.m */; };
|
||||
74321DCB1C2D939A00CF6F43 /* SocketAckManagerTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74321DC91C2D939A00CF6F43 /* SocketAckManagerTest.swift */; };
|
||||
74321DCC1C2D939A00CF6F43 /* SocketParserTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74321DCA1C2D939A00CF6F43 /* SocketParserTest.swift */; };
|
||||
7471CCEA1C39926300364B59 /* SocketClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketClientSpec.swift */; };
|
||||
7471CCEB1C39926C00364B59 /* SocketClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketClientSpec.swift */; };
|
||||
7471CCEA1C39926300364B59 /* SocketIOClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */; };
|
||||
7471CCEB1C39926C00364B59 /* SocketIOClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */; };
|
||||
7472C65C1BCAB53E003CA70D /* SocketNamespacePacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */; };
|
||||
7472C65D1BCAB53E003CA70D /* SocketNamespacePacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */; };
|
||||
7472C65F1BCAC46E003CA70D /* SocketSideEffectTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */; };
|
||||
7472C6601BCAC46E003CA70D /* SocketSideEffectTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */; };
|
||||
74ABF7771C3991C10078C657 /* SocketClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketClientSpec.swift */; };
|
||||
74ABF7771C3991C10078C657 /* SocketIOClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */; };
|
||||
74B4AD1D1D09A5D80062A523 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74B4AD1C1D09A5D80062A523 /* WebSocket.swift */; };
|
||||
74B4AD211D09A6190062A523 /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74B4AD201D09A6190062A523 /* SSLSecurity.swift */; };
|
||||
74B4AD221D09A6190062A523 /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74B4AD201D09A6190062A523 /* SSLSecurity.swift */; };
|
||||
74B4AD231D09A6190062A523 /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74B4AD201D09A6190062A523 /* SSLSecurity.swift */; };
|
||||
74B4AD241D09A6450062A523 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74B4AD1C1D09A5D80062A523 /* WebSocket.swift */; };
|
||||
74B4AD251D09A6490062A523 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74B4AD1C1D09A5D80062A523 /* WebSocket.swift */; };
|
||||
74BC45AB1D0C6675008CC431 /* SocketClientManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74BC45AA1D0C6675008CC431 /* SocketClientManager.swift */; };
|
||||
74BC45AC1D0C6675008CC431 /* SocketClientManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74BC45AA1D0C6675008CC431 /* SocketClientManager.swift */; };
|
||||
74BC45AD1D0C6675008CC431 /* SocketClientManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74BC45AA1D0C6675008CC431 /* SocketClientManager.swift */; };
|
||||
74F124F01BC574CF002966F4 /* SocketBasicPacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */; };
|
||||
74F124F11BC574CF002966F4 /* SocketBasicPacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */; };
|
||||
CEBA56961CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */; };
|
||||
CEBA56971CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */; };
|
||||
CEBA56981CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */; };
|
||||
CEBA569A1CDA0B8200BA0389 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* String.swift */; };
|
||||
CEBA569B1CDA0B8200BA0389 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* String.swift */; };
|
||||
CEBA569C1CDA0B8200BA0389 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* String.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@@ -163,7 +164,6 @@
|
||||
572EF21D1B51F16C00EEBB58 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
572EF21E1B51F16C00EEBB58 /* SocketIO-iOS.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "SocketIO-iOS.h"; sourceTree = "<group>"; };
|
||||
572EF2241B51F16C00EEBB58 /* SocketIO-iOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SocketIO-iOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
572EF22A1B51F16C00EEBB58 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
572EF2381B51F18A00EEBB58 /* SocketIOClientSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SocketIOClientSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
572EF23B1B51F18A00EEBB58 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
572EF23C1B51F18A00EEBB58 /* SocketIO-Mac.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "SocketIO-Mac.h"; sourceTree = "<group>"; };
|
||||
@@ -180,7 +180,6 @@
|
||||
74171E551C10CD240062D398 /* SocketEnginePacketType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketEnginePacketType.swift; path = Source/SocketEnginePacketType.swift; sourceTree = "<group>"; };
|
||||
74171E561C10CD240062D398 /* SocketEngineSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketEngineSpec.swift; path = Source/SocketEngineSpec.swift; sourceTree = "<group>"; };
|
||||
74171E571C10CD240062D398 /* SocketEventHandler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketEventHandler.swift; path = Source/SocketEventHandler.swift; sourceTree = "<group>"; };
|
||||
74171E581C10CD240062D398 /* SocketFixUTF8.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketFixUTF8.swift; path = Source/SocketFixUTF8.swift; sourceTree = "<group>"; };
|
||||
74171E591C10CD240062D398 /* SocketIOClient.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClient.swift; path = Source/SocketIOClient.swift; sourceTree = "<group>"; };
|
||||
74171E5A1C10CD240062D398 /* SocketIOClientOption.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClientOption.swift; path = Source/SocketIOClientOption.swift; sourceTree = "<group>"; };
|
||||
74171E5B1C10CD240062D398 /* SocketIOClientStatus.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClientStatus.swift; path = Source/SocketIOClientStatus.swift; sourceTree = "<group>"; };
|
||||
@@ -189,16 +188,20 @@
|
||||
74171E5E1C10CD240062D398 /* SocketParsable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketParsable.swift; path = Source/SocketParsable.swift; sourceTree = "<group>"; };
|
||||
74171E5F1C10CD240062D398 /* SocketStringReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketStringReader.swift; path = Source/SocketStringReader.swift; sourceTree = "<group>"; };
|
||||
74171E601C10CD240062D398 /* SocketTypes.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketTypes.swift; path = Source/SocketTypes.swift; sourceTree = "<group>"; };
|
||||
74171E611C10CD240062D398 /* SwiftRegex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SwiftRegex.swift; path = Source/SwiftRegex.swift; sourceTree = "<group>"; };
|
||||
74171E621C10CD240062D398 /* WebSocket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = Source/WebSocket.swift; sourceTree = "<group>"; };
|
||||
741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketEngineTest.swift; sourceTree = "<group>"; };
|
||||
7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketEnginePollable.swift; path = Source/SocketEnginePollable.swift; sourceTree = "<group>"; };
|
||||
742D150B1CA5794B00BD987D /* SocketObjectiveCTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SocketObjectiveCTest.m; sourceTree = "<group>"; };
|
||||
74321DC91C2D939A00CF6F43 /* SocketAckManagerTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SocketAckManagerTest.swift; sourceTree = "<group>"; };
|
||||
74321DCA1C2D939A00CF6F43 /* SocketParserTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SocketParserTest.swift; sourceTree = "<group>"; };
|
||||
7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketNamespacePacketTest.swift; sourceTree = "<group>"; };
|
||||
7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketSideEffectTest.swift; sourceTree = "<group>"; };
|
||||
74ABF7761C3991C10078C657 /* SocketClientSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketClientSpec.swift; path = Source/SocketClientSpec.swift; sourceTree = "<group>"; };
|
||||
74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClientSpec.swift; path = Source/SocketIOClientSpec.swift; sourceTree = "<group>"; };
|
||||
74B4AD1C1D09A5D80062A523 /* WebSocket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = Source/WebSocket/WebSocket.swift; sourceTree = "<group>"; };
|
||||
74B4AD201D09A6190062A523 /* SSLSecurity.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SSLSecurity.swift; path = Source/WebSocket/SSLSecurity.swift; sourceTree = "<group>"; };
|
||||
74BC45AA1D0C6675008CC431 /* SocketClientManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketClientManager.swift; path = Source/SocketClientManager.swift; sourceTree = "<group>"; };
|
||||
74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketBasicPacketTest.swift; sourceTree = "<group>"; };
|
||||
CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = NSCharacterSet.swift; path = Source/NSCharacterSet.swift; sourceTree = "<group>"; };
|
||||
CEBA56991CDA0B8200BA0389 /* String.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = String.swift; path = Source/String.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -255,7 +258,6 @@
|
||||
children = (
|
||||
5764DF7B1B51F24A004FF46E /* Source */,
|
||||
572EF21B1B51F16C00EEBB58 /* SocketIO-iOS */,
|
||||
572EF2281B51F16C00EEBB58 /* SocketIO-iOSTests */,
|
||||
572EF2391B51F18A00EEBB58 /* SocketIO-Mac */,
|
||||
572EF2461B51F18A00EEBB58 /* SocketIO-MacTests */,
|
||||
572EF21A1B51F16C00EEBB58 /* Products */,
|
||||
@@ -292,22 +294,6 @@
|
||||
name = "Supporting Files";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
572EF2281B51F16C00EEBB58 /* SocketIO-iOSTests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
572EF2291B51F16C00EEBB58 /* Supporting Files */,
|
||||
);
|
||||
path = "SocketIO-iOSTests";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
572EF2291B51F16C00EEBB58 /* Supporting Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
572EF22A1B51F16C00EEBB58 /* Info.plist */,
|
||||
);
|
||||
name = "Supporting Files";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
572EF2391B51F18A00EEBB58 /* SocketIO-Mac */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -332,6 +318,7 @@
|
||||
74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */,
|
||||
741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */,
|
||||
7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */,
|
||||
742D150B1CA5794B00BD987D /* SocketObjectiveCTest.m */,
|
||||
74321DCA1C2D939A00CF6F43 /* SocketParserTest.swift */,
|
||||
7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */,
|
||||
572EF2471B51F18A00EEBB58 /* Supporting Files */,
|
||||
@@ -353,7 +340,7 @@
|
||||
74171E501C10CD240062D398 /* SocketAckEmitter.swift */,
|
||||
74171E511C10CD240062D398 /* SocketAckManager.swift */,
|
||||
74171E521C10CD240062D398 /* SocketAnyEvent.swift */,
|
||||
74ABF7761C3991C10078C657 /* SocketClientSpec.swift */,
|
||||
74BC45AA1D0C6675008CC431 /* SocketClientManager.swift */,
|
||||
74171E531C10CD240062D398 /* SocketEngine.swift */,
|
||||
74171E541C10CD240062D398 /* SocketEngineClient.swift */,
|
||||
74171E551C10CD240062D398 /* SocketEnginePacketType.swift */,
|
||||
@@ -361,21 +348,39 @@
|
||||
74171E561C10CD240062D398 /* SocketEngineSpec.swift */,
|
||||
740CA11F1C496EEB00CB98F4 /* SocketEngineWebsocket.swift */,
|
||||
74171E571C10CD240062D398 /* SocketEventHandler.swift */,
|
||||
74171E581C10CD240062D398 /* SocketFixUTF8.swift */,
|
||||
74171E591C10CD240062D398 /* SocketIOClient.swift */,
|
||||
74171E5A1C10CD240062D398 /* SocketIOClientOption.swift */,
|
||||
74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */,
|
||||
74171E5B1C10CD240062D398 /* SocketIOClientStatus.swift */,
|
||||
74171E5C1C10CD240062D398 /* SocketLogger.swift */,
|
||||
74171E5D1C10CD240062D398 /* SocketPacket.swift */,
|
||||
74171E5E1C10CD240062D398 /* SocketParsable.swift */,
|
||||
74171E5F1C10CD240062D398 /* SocketStringReader.swift */,
|
||||
74171E601C10CD240062D398 /* SocketTypes.swift */,
|
||||
74171E611C10CD240062D398 /* SwiftRegex.swift */,
|
||||
74171E621C10CD240062D398 /* WebSocket.swift */,
|
||||
CEBA569E1CDA0C0C00BA0389 /* utils */,
|
||||
74B4AD1B1D09A5C30062A523 /* Websocket */,
|
||||
);
|
||||
name = Source;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
74B4AD1B1D09A5C30062A523 /* Websocket */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
74B4AD1C1D09A5D80062A523 /* WebSocket.swift */,
|
||||
74B4AD201D09A6190062A523 /* SSLSecurity.swift */,
|
||||
);
|
||||
name = Websocket;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
CEBA569E1CDA0C0C00BA0389 /* utils */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */,
|
||||
CEBA56991CDA0B8200BA0389 /* String.swift */,
|
||||
);
|
||||
name = utils;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXHeadersBuildPhase section */
|
||||
@@ -520,7 +525,7 @@
|
||||
572EF20E1B51F12F00EEBB58 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 0710;
|
||||
LastSwiftUpdateCheck = 0730;
|
||||
LastUpgradeCheck = 0720;
|
||||
TargetAttributes = {
|
||||
572EF2181B51F16C00EEBB58 = {
|
||||
@@ -610,27 +615,29 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
740CA1221C496EF700CB98F4 /* SocketEngineWebsocket.swift in Sources */,
|
||||
74171E931C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
|
||||
74171EA51C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
|
||||
CEBA569A1CDA0B8200BA0389 /* String.swift in Sources */,
|
||||
74B4AD1D1D09A5D80062A523 /* WebSocket.swift in Sources */,
|
||||
74171E751C10CD240062D398 /* SocketEngine.swift in Sources */,
|
||||
74171E691C10CD240062D398 /* SocketAckManager.swift in Sources */,
|
||||
7420CB791C49629E00956AA4 /* SocketEnginePollable.swift in Sources */,
|
||||
74ABF7771C3991C10078C657 /* SocketClientSpec.swift in Sources */,
|
||||
CEBA56961CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */,
|
||||
74ABF7771C3991C10078C657 /* SocketIOClientSpec.swift in Sources */,
|
||||
74171E871C10CD240062D398 /* SocketEngineSpec.swift in Sources */,
|
||||
74171E631C10CD240062D398 /* SocketAckEmitter.swift in Sources */,
|
||||
74B4AD211D09A6190062A523 /* SSLSecurity.swift in Sources */,
|
||||
74171EBD1C10CD240062D398 /* SocketStringReader.swift in Sources */,
|
||||
74171EC31C10CD240062D398 /* SocketTypes.swift in Sources */,
|
||||
74171EAB1C10CD240062D398 /* SocketLogger.swift in Sources */,
|
||||
74171E991C10CD240062D398 /* SocketIOClient.swift in Sources */,
|
||||
74171E8D1C10CD240062D398 /* SocketEventHandler.swift in Sources */,
|
||||
74171EC91C10CD240062D398 /* SwiftRegex.swift in Sources */,
|
||||
74171E7B1C10CD240062D398 /* SocketEngineClient.swift in Sources */,
|
||||
74171ECF1C10CD240062D398 /* WebSocket.swift in Sources */,
|
||||
74171EB11C10CD240062D398 /* SocketPacket.swift in Sources */,
|
||||
74171EB71C10CD240062D398 /* SocketParsable.swift in Sources */,
|
||||
74171E811C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
|
||||
74171E6F1C10CD240062D398 /* SocketAnyEvent.swift in Sources */,
|
||||
74171E9F1C10CD240062D398 /* SocketIOClientOption.swift in Sources */,
|
||||
74BC45AB1D0C6675008CC431 /* SocketClientManager.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -641,15 +648,12 @@
|
||||
7472C65F1BCAC46E003CA70D /* SocketSideEffectTest.swift in Sources */,
|
||||
74171EA61C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
|
||||
74171E881C10CD240062D398 /* SocketEngineSpec.swift in Sources */,
|
||||
74171ED01C10CD240062D398 /* WebSocket.swift in Sources */,
|
||||
74171EA01C10CD240062D398 /* SocketIOClientOption.swift in Sources */,
|
||||
74171E701C10CD240062D398 /* SocketAnyEvent.swift in Sources */,
|
||||
74171EC41C10CD240062D398 /* SocketTypes.swift in Sources */,
|
||||
74171E8E1C10CD240062D398 /* SocketEventHandler.swift in Sources */,
|
||||
74171E7C1C10CD240062D398 /* SocketEngineClient.swift in Sources */,
|
||||
74171E941C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
|
||||
74171E821C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
|
||||
74171ECA1C10CD240062D398 /* SwiftRegex.swift in Sources */,
|
||||
74171EB21C10CD240062D398 /* SocketPacket.swift in Sources */,
|
||||
741F39EE1BD025D80026C9CC /* SocketEngineTest.swift in Sources */,
|
||||
74171EBE1C10CD240062D398 /* SocketStringReader.swift in Sources */,
|
||||
@@ -668,12 +672,14 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
74B4AD241D09A6450062A523 /* WebSocket.swift in Sources */,
|
||||
740CA1211C496EF200CB98F4 /* SocketEngineWebsocket.swift in Sources */,
|
||||
7471CCEA1C39926300364B59 /* SocketClientSpec.swift in Sources */,
|
||||
74171E951C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
|
||||
7471CCEA1C39926300364B59 /* SocketIOClientSpec.swift in Sources */,
|
||||
CEBA569B1CDA0B8200BA0389 /* String.swift in Sources */,
|
||||
74171EA71C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
|
||||
74171E771C10CD240062D398 /* SocketEngine.swift in Sources */,
|
||||
7420CB7A1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */,
|
||||
CEBA56971CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */,
|
||||
74171E6B1C10CD240062D398 /* SocketAckManager.swift in Sources */,
|
||||
74171E891C10CD240062D398 /* SocketEngineSpec.swift in Sources */,
|
||||
74171E651C10CD240062D398 /* SocketAckEmitter.swift in Sources */,
|
||||
@@ -682,14 +688,14 @@
|
||||
74171EAD1C10CD240062D398 /* SocketLogger.swift in Sources */,
|
||||
74171E9B1C10CD240062D398 /* SocketIOClient.swift in Sources */,
|
||||
74171E8F1C10CD240062D398 /* SocketEventHandler.swift in Sources */,
|
||||
74171ECB1C10CD240062D398 /* SwiftRegex.swift in Sources */,
|
||||
74171E7D1C10CD240062D398 /* SocketEngineClient.swift in Sources */,
|
||||
74171ED11C10CD240062D398 /* WebSocket.swift in Sources */,
|
||||
74B4AD221D09A6190062A523 /* SSLSecurity.swift in Sources */,
|
||||
74171EB31C10CD240062D398 /* SocketPacket.swift in Sources */,
|
||||
74171EB91C10CD240062D398 /* SocketParsable.swift in Sources */,
|
||||
74171E831C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
|
||||
74171E711C10CD240062D398 /* SocketAnyEvent.swift in Sources */,
|
||||
74171EA11C10CD240062D398 /* SocketIOClientOption.swift in Sources */,
|
||||
74BC45AC1D0C6675008CC431 /* SocketClientManager.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -697,6 +703,7 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
742D150C1CA5794B00BD987D /* SocketObjectiveCTest.m in Sources */,
|
||||
74321DCB1C2D939A00CF6F43 /* SocketAckManagerTest.swift in Sources */,
|
||||
74321DCC1C2D939A00CF6F43 /* SocketParserTest.swift in Sources */,
|
||||
7472C6601BCAC46E003CA70D /* SocketSideEffectTest.swift in Sources */,
|
||||
@@ -711,12 +718,14 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
74B4AD251D09A6490062A523 /* WebSocket.swift in Sources */,
|
||||
740CA1201C496EEB00CB98F4 /* SocketEngineWebsocket.swift in Sources */,
|
||||
7471CCEB1C39926C00364B59 /* SocketClientSpec.swift in Sources */,
|
||||
74171E971C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
|
||||
7471CCEB1C39926C00364B59 /* SocketIOClientSpec.swift in Sources */,
|
||||
CEBA569C1CDA0B8200BA0389 /* String.swift in Sources */,
|
||||
74171EA91C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
|
||||
74171E791C10CD240062D398 /* SocketEngine.swift in Sources */,
|
||||
7420CB7B1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */,
|
||||
CEBA56981CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */,
|
||||
74171E6D1C10CD240062D398 /* SocketAckManager.swift in Sources */,
|
||||
74171E8B1C10CD240062D398 /* SocketEngineSpec.swift in Sources */,
|
||||
74171E671C10CD240062D398 /* SocketAckEmitter.swift in Sources */,
|
||||
@@ -725,14 +734,14 @@
|
||||
74171EAF1C10CD240062D398 /* SocketLogger.swift in Sources */,
|
||||
74171E9D1C10CD240062D398 /* SocketIOClient.swift in Sources */,
|
||||
74171E911C10CD240062D398 /* SocketEventHandler.swift in Sources */,
|
||||
74171ECD1C10CD240062D398 /* SwiftRegex.swift in Sources */,
|
||||
74171E7F1C10CD240062D398 /* SocketEngineClient.swift in Sources */,
|
||||
74171ED31C10CD240062D398 /* WebSocket.swift in Sources */,
|
||||
74B4AD231D09A6190062A523 /* SSLSecurity.swift in Sources */,
|
||||
74171EB51C10CD240062D398 /* SocketPacket.swift in Sources */,
|
||||
74171EBB1C10CD240062D398 /* SocketParsable.swift in Sources */,
|
||||
74171E851C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
|
||||
74171E731C10CD240062D398 /* SocketAnyEvent.swift in Sources */,
|
||||
74171EA31C10CD240062D398 /* SocketIOClientOption.swift in Sources */,
|
||||
74BC45AD1D0C6675008CC431 /* SocketClientManager.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -743,15 +752,12 @@
|
||||
57634A231BD9B46D00E19CD7 /* SocketSideEffectTest.swift in Sources */,
|
||||
74171EAA1C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
|
||||
74171E8C1C10CD240062D398 /* SocketEngineSpec.swift in Sources */,
|
||||
74171ED41C10CD240062D398 /* WebSocket.swift in Sources */,
|
||||
74171EA41C10CD240062D398 /* SocketIOClientOption.swift in Sources */,
|
||||
74171E741C10CD240062D398 /* SocketAnyEvent.swift in Sources */,
|
||||
74171EC81C10CD240062D398 /* SocketTypes.swift in Sources */,
|
||||
74171E921C10CD240062D398 /* SocketEventHandler.swift in Sources */,
|
||||
74171E801C10CD240062D398 /* SocketEngineClient.swift in Sources */,
|
||||
74171E981C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
|
||||
74171E861C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
|
||||
74171ECE1C10CD240062D398 /* SwiftRegex.swift in Sources */,
|
||||
74171EB61C10CD240062D398 /* SocketPacket.swift in Sources */,
|
||||
57634A2A1BD9B46D00E19CD7 /* SocketEngineTest.swift in Sources */,
|
||||
74171EC21C10CD240062D398 /* SocketStringReader.swift in Sources */,
|
||||
@@ -1181,6 +1187,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -1281,7 +1288,7 @@
|
||||
SDKROOT = appletvos;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TARGETED_DEVICE_FAMILY = 3;
|
||||
TVOS_DEPLOYMENT_TARGET = 9.0;
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
VERSION_INFO_PREFIX = "";
|
||||
@@ -1332,7 +1339,7 @@
|
||||
PRODUCT_NAME = SocketIO;
|
||||
SDKROOT = appletvos;
|
||||
SKIP_INSTALL = YES;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TARGETED_DEVICE_FAMILY = 3;
|
||||
TVOS_DEPLOYMENT_TARGET = 9.0;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
|
||||
@@ -37,6 +37,14 @@ class SocketBasicPacketTest: XCTestCase {
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testStringEmitWithQuotes() {
|
||||
let expectedSendString = "2[\"test\",\"\\\"he\\\"llo world\\\"\"]"
|
||||
let sendData = ["test", "\"he\"llo world\""]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testJSONEmit() {
|
||||
let expectedSendString = "2[\"test\",{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
|
||||
let sendData = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
|
||||
@@ -137,4 +145,20 @@ class SocketBasicPacketTest: XCTestCase {
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data2, data])
|
||||
}
|
||||
|
||||
func testBinaryStringPlaceholderInMessage() {
|
||||
let engineString = "52-[\"test\",\"~~0\",{\"num\":0,\"_placeholder\":true},{\"num\":1,\"_placeholder\":true}]"
|
||||
let socket = SocketIOClient(socketURL: NSURL())
|
||||
socket.setTestable()
|
||||
|
||||
if case let .Right(packet) = socket.parseString(engineString) {
|
||||
var packet = packet
|
||||
XCTAssertEqual(packet.event, "test")
|
||||
packet.addData(data)
|
||||
packet.addData(data2)
|
||||
XCTAssertEqual(packet.args[0] as? String, "~~0")
|
||||
} else {
|
||||
XCTFail()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,8 @@ class SocketEngineTest: XCTestCase {
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
client = SocketIOClient(socketURL: "")
|
||||
engine = SocketEngine(client: client, url: "", options: nil)
|
||||
client = SocketIOClient(socketURL: NSURL(string: "http://localhost")!)
|
||||
engine = SocketEngine(client: client, url: NSURL(string: "http://localhost")!, options: nil)
|
||||
|
||||
client.setTestable()
|
||||
}
|
||||
@@ -74,4 +74,32 @@ class SocketEngineTest: XCTestCase {
|
||||
engine.parseEngineMessage("afafafda", fromPolling: false)
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testEngineDecodesUTF8Properly() {
|
||||
let expectation = expectationWithDescription("Engine Decodes utf8")
|
||||
|
||||
client.on("stringTest") {data, ack in
|
||||
XCTAssertEqual(data[0] as? String, "lïne one\nlīne \rtwo", "Failed string test")
|
||||
expectation.fulfill()
|
||||
}
|
||||
|
||||
engine.parsePollingMessage("41:42[\"stringTest\",\"lïne one\\nlīne \\rtwo\"]")
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testEncodeURLProperly() {
|
||||
engine.connectParams = [
|
||||
"created": "2016-05-04T18:31:15+0200"
|
||||
]
|
||||
|
||||
XCTAssertEqual(engine.urlPolling.query, "transport=polling&b64=1&created=2016-05-04T18%3A31%3A15%2B0200")
|
||||
XCTAssertEqual(engine.urlWebSocket.query, "transport=websocket&created=2016-05-04T18%3A31%3A15%2B0200")
|
||||
|
||||
engine.connectParams = [
|
||||
"forbidden": "!*'();:@&=+$,/?%#[]\" {}"
|
||||
]
|
||||
|
||||
XCTAssertEqual(engine.urlPolling.query, "transport=polling&b64=1&forbidden=%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D%22%20%7B%7D")
|
||||
XCTAssertEqual(engine.urlWebSocket.query, "transport=websocket&forbidden=%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D%22%20%7B%7D")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//
|
||||
// SocketObjectiveCTest.m
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/25/16.
|
||||
//
|
||||
// Merely tests whether the Objective-C api breaks
|
||||
//
|
||||
|
||||
#import <XCTest/XCTest.h>
|
||||
@import SocketIOClientSwift;
|
||||
|
||||
@interface SocketObjectiveCTest : XCTestCase
|
||||
|
||||
@property SocketIOClient* socket;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SocketObjectiveCTest
|
||||
|
||||
- (void)setUp {
|
||||
[super setUp];
|
||||
NSURL* url = [[NSURL alloc] initWithString:@"http://localhost"];
|
||||
self.socket = [[SocketIOClient alloc] initWithSocketURL:url options:nil];
|
||||
}
|
||||
|
||||
- (void)testOnSyntax {
|
||||
[self.socket on:@"someCallback" callback:^(NSArray* data, SocketAckEmitter* ack) {
|
||||
[ack with:@[@1]];
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)testEmitSyntax {
|
||||
[self.socket emit:@"testEmit" withItems:@[@YES]];
|
||||
}
|
||||
|
||||
- (void)testEmitWithAckSyntax {
|
||||
[self.socket emitWithAck:@"testAckEmit" withItems:@[@YES]](0, ^(NSArray* data) {
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
- (void)testOffSyntax {
|
||||
[self.socket off:@"test"];
|
||||
}
|
||||
|
||||
- (void)testSocketManager {
|
||||
SocketClientManager* manager = [SocketClientManager sharedManager];
|
||||
[manager addSocket:self.socket labeledAs:@"test"];
|
||||
[manager removeSocketWithLabel:@"test"];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -10,21 +10,23 @@ import XCTest
|
||||
@testable import SocketIOClientSwift
|
||||
|
||||
class SocketParserTest: XCTestCase {
|
||||
let testSocket = SocketIOClient(socketURL: "")
|
||||
let testSocket = SocketIOClient(socketURL: NSURL())
|
||||
|
||||
//Format key: message; namespace-data-binary-id
|
||||
static let packetTypes: Dictionary<String, (String, [AnyObject], [NSData], Int)> = [
|
||||
static let packetTypes: [String: (String, [AnyObject], [NSData], Int)] = [
|
||||
"0": ("/", [], [], -1), "1": ("/", [], [], -1),
|
||||
"25[\"test\"]": ("/", ["test"], [], 5),
|
||||
"2[\"test\",\"~~0\"]": ("/", ["test", "~~0"], [], -1),
|
||||
"2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]": ("/swift", ["testArrayEmitReturn", ["test3", "test4"]], [], -1),
|
||||
"51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", ["testMultipleItemsWithBufferEmitReturn", [1, 2], ["test": "bob"], 25, "polo", "~~0"], [], -1),
|
||||
"51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", ["testMultipleItemsWithBufferEmitReturn", [1, 2], ["test": "bob"], 25, "polo", ["_placeholder": true, "num": 0]], [], -1),
|
||||
"3/swift,0[[\"test3\",\"test4\"]]": ("/swift", [["test3", "test4"]], [], 0),
|
||||
"61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", [ [1, 2], ["test": "bob"], 25, "polo", "~~0"], [], 19),
|
||||
"61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]":
|
||||
("/swift", [ [1, 2], ["test": "bob"], 25, "polo", ["_placeholder": true, "num": 0]], [], 19),
|
||||
"4/swift,": ("/swift", [], [], -1),
|
||||
"0/swift": ("/swift", [], [], -1),
|
||||
"1/swift": ("/swift", [], [], -1),
|
||||
"4\"ERROR\"": ("/", ["ERROR"], [], -1),
|
||||
"4{\"test\":2}": ("/", [["test": 2]], [], -1),
|
||||
"41": ("/", [1], [], -1)]
|
||||
|
||||
func testDisconnect() {
|
||||
@@ -87,6 +89,11 @@ class SocketParserTest: XCTestCase {
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testErrorTypeDictionary() {
|
||||
let message = "4{\"test\":2}"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testErrorTypeInt() {
|
||||
let message = "41"
|
||||
validateParseResult(message)
|
||||
@@ -113,12 +120,12 @@ class SocketParserTest: XCTestCase {
|
||||
func validateParseResult(message: String) {
|
||||
let validValues = SocketParserTest.packetTypes[message]!
|
||||
let packet = testSocket.parseString(message)
|
||||
let type = message.substringWithRange(Range<String.Index>(start: message.startIndex, end: message.startIndex.advancedBy(1)))
|
||||
let type = message.substringWithRange(Range<String.Index>(message.startIndex..<message.startIndex.advancedBy(1)))
|
||||
if case let .Right(packet) = packet {
|
||||
XCTAssertEqual(packet.type, SocketPacket.PacketType(rawValue: Int(type) ?? -1)!)
|
||||
XCTAssertEqual(packet.nsp, validValues.0)
|
||||
XCTAssertTrue((packet.data as NSArray).isEqualToArray(validValues.1))
|
||||
XCTAssertTrue((packet.binary as NSArray).isEqualToArray(validValues.2))
|
||||
XCTAssertTrue((packet.data as NSArray).isEqualToArray(validValues.1), "\(packet.data)")
|
||||
XCTAssertTrue((packet.binary as NSArray).isEqualToArray(validValues.2), "\(packet.binary)")
|
||||
XCTAssertEqual(packet.id, validValues.3)
|
||||
} else {
|
||||
XCTFail()
|
||||
|
||||
@@ -16,7 +16,7 @@ class SocketSideEffectTest: XCTestCase {
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
socket = SocketIOClient(socketURL: "")
|
||||
socket = SocketIOClient(socketURL: NSURL())
|
||||
socket.setTestable()
|
||||
}
|
||||
|
||||
@@ -70,6 +70,17 @@ class SocketSideEffectTest: XCTestCase {
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testHandleStringEventWithQuotes() {
|
||||
let expectation = expectationWithDescription("handled event")
|
||||
socket.on("test") {data, ack in
|
||||
XCTAssertEqual(data[0] as? String, "\"hello world\"")
|
||||
expectation.fulfill()
|
||||
}
|
||||
|
||||
socket.parseSocketMessage("2[\"test\",\"\\\"hello world\\\"\"]")
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testHandleOnceEvent() {
|
||||
let expectation = expectationWithDescription("handled event")
|
||||
socket.once("test") {data, ack in
|
||||
@@ -142,4 +153,16 @@ class SocketSideEffectTest: XCTestCase {
|
||||
socket.parseBinaryData(data2)
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testSocketManager() {
|
||||
let manager = SocketClientManager.sharedManager
|
||||
manager["test"] = socket
|
||||
|
||||
XCTAssert(manager["test"] === socket, "failed to get socket")
|
||||
|
||||
manager["test"] = nil
|
||||
|
||||
XCTAssert(manager["test"] == nil, "socket not removed")
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>BNDL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,8 +1,8 @@
|
||||
//
|
||||
// SocketFixUTF8.swift
|
||||
// NSCharacterSet.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/16/15.
|
||||
// Created by Yannick Loriot on 5/4/16.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
@@ -21,24 +21,11 @@
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
func fixDoubleUTF8(string: String) -> String {
|
||||
if let utf8 = string.dataUsingEncoding(NSISOLatin1StringEncoding),
|
||||
latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding) {
|
||||
return latin1 as String
|
||||
} else {
|
||||
return string
|
||||
}
|
||||
}
|
||||
|
||||
func doubleEncodeUTF8(string: String) -> String {
|
||||
if let latin1 = string.dataUsingEncoding(NSUTF8StringEncoding),
|
||||
utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding) {
|
||||
return utf8 as String
|
||||
} else {
|
||||
return string
|
||||
}
|
||||
extension NSCharacterSet {
|
||||
class var allowedURLCharacterSet: NSCharacterSet {
|
||||
return NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
public final class SocketAckEmitter: NSObject {
|
||||
public final class SocketAckEmitter : NSObject {
|
||||
let socket: SocketIOClient
|
||||
let ackNum: Int
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
private struct SocketAck: Hashable, Equatable {
|
||||
private struct SocketAck : Hashable, Equatable {
|
||||
let ack: Int
|
||||
var callback: AckCallback!
|
||||
var hashValue: Int {
|
||||
|
||||
@@ -24,8 +24,8 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
@objc public final class SocketAnyEvent: NSObject {
|
||||
public let event: String!
|
||||
public final class SocketAnyEvent : NSObject {
|
||||
public let event: String
|
||||
public let items: NSArray?
|
||||
override public var description: String {
|
||||
return "SocketAnyEvent: Event: \(event) items: \(items ?? nil)"
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
//
|
||||
// SocketClientManager.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 6/11/16.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Experimental socket manager.
|
||||
|
||||
API subject to change.
|
||||
|
||||
Can be used to persist sockets across ViewControllers.
|
||||
|
||||
Sockets are strongly stored, so be sure to remove them once they are no
|
||||
longer needed.
|
||||
|
||||
Example usage:
|
||||
```
|
||||
let manager = SocketClientManager.sharedManager
|
||||
manager["room1"] = socket1
|
||||
manager["room2"] = socket2
|
||||
manager.removeSocket(socket: socket2)
|
||||
manager["room1"]?.emit("hello")
|
||||
```
|
||||
*/
|
||||
public final class SocketClientManager : NSObject {
|
||||
public static let sharedManager = SocketClientManager()
|
||||
|
||||
private var sockets = [String: SocketIOClient]()
|
||||
|
||||
public subscript(string: String) -> SocketIOClient? {
|
||||
get {
|
||||
return sockets[string]
|
||||
}
|
||||
|
||||
set(socket) {
|
||||
sockets[string] = socket
|
||||
}
|
||||
}
|
||||
|
||||
public func addSocket(socket: SocketIOClient, labeledAs label: String) {
|
||||
sockets[label] = socket
|
||||
}
|
||||
|
||||
public func removeSocket(withLabel label: String) -> SocketIOClient? {
|
||||
return sockets.removeValueForKey(label)
|
||||
}
|
||||
|
||||
public func removeSocket(socket socket: SocketIOClient) -> SocketIOClient? {
|
||||
var returnSocket: SocketIOClient?
|
||||
|
||||
for (label, dictSocket) in sockets where dictSocket === socket {
|
||||
returnSocket = sockets.removeValueForKey(label)
|
||||
}
|
||||
|
||||
return returnSocket
|
||||
}
|
||||
|
||||
public func removeSockets() {
|
||||
sockets.removeAll()
|
||||
}
|
||||
}
|
||||
+171
-176
@@ -24,11 +24,17 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWebsocket {
|
||||
public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWebsocket {
|
||||
public let emitQueue = dispatch_queue_create("com.socketio.engineEmitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
public let handleQueue = dispatch_queue_create("com.socketio.engineHandleQueue", DISPATCH_QUEUE_SERIAL)
|
||||
public let parseQueue = dispatch_queue_create("com.socketio.engineParseQueue", DISPATCH_QUEUE_SERIAL)
|
||||
|
||||
public var connectParams: [String: AnyObject]? {
|
||||
didSet {
|
||||
(urlPolling, urlWebSocket) = createURLs()
|
||||
}
|
||||
}
|
||||
|
||||
public var postWait = [String]()
|
||||
public var waitingForPoll = false
|
||||
public var waitingForPost = false
|
||||
@@ -36,19 +42,19 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
public private(set) var closed = false
|
||||
public private(set) var connected = false
|
||||
public private(set) var cookies: [NSHTTPCookie]?
|
||||
public private(set) var doubleEncodeUTF8 = true
|
||||
public private(set) var extraHeaders: [String: String]?
|
||||
public private(set) var fastUpgrade = false
|
||||
public private(set) var forcePolling = false
|
||||
public private(set) var forceWebsockets = false
|
||||
public private(set) var invalidated = false
|
||||
public private(set) var pingTimer: NSTimer?
|
||||
public private(set) var polling = true
|
||||
public private(set) var probing = false
|
||||
public private(set) var session: NSURLSession?
|
||||
public private(set) var sid = ""
|
||||
public private(set) var socketPath = "/engine.io"
|
||||
public private(set) var urlPolling = ""
|
||||
public private(set) var urlWebSocket = ""
|
||||
public private(set) var socketPath = "/engine.io/"
|
||||
public private(set) var urlPolling = NSURL()
|
||||
public private(set) var urlWebSocket = NSURL()
|
||||
public private(set) var websocket = false
|
||||
public private(set) var ws: WebSocket?
|
||||
|
||||
@@ -56,64 +62,70 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
|
||||
private weak var sessionDelegate: NSURLSessionDelegate?
|
||||
|
||||
private typealias Probe = (msg: String, type: SocketEnginePacketType, data: [NSData])
|
||||
private typealias ProbeWaitQueue = [Probe]
|
||||
|
||||
private let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
|
||||
private let logType = "SocketEngine"
|
||||
private let url: String
|
||||
private let url: NSURL
|
||||
|
||||
private var connectParams: [String: AnyObject]?
|
||||
private var pingInterval: Double?
|
||||
private var pingTimeout = 0.0 {
|
||||
didSet {
|
||||
pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25))
|
||||
}
|
||||
}
|
||||
|
||||
private var pongsMissed = 0
|
||||
private var pongsMissedMax = 0
|
||||
private var probeWait = ProbeWaitQueue()
|
||||
private var secure = false
|
||||
private var security: SSLSecurity?
|
||||
private var selfSigned = false
|
||||
private var voipEnabled = false
|
||||
|
||||
public init(client: SocketEngineClient, url: String, options: Set<SocketIOClientOption>) {
|
||||
|
||||
public init(client: SocketEngineClient, url: NSURL, options: Set<SocketIOClientOption>) {
|
||||
self.client = client
|
||||
self.url = url
|
||||
|
||||
|
||||
for option in options {
|
||||
switch option {
|
||||
case let .ConnectParams(params):
|
||||
connectParams = params
|
||||
case let .Cookies(cookies):
|
||||
self.cookies = cookies
|
||||
case let .DoubleEncodeUTF8(encode):
|
||||
doubleEncodeUTF8 = encode
|
||||
case let .ExtraHeaders(headers):
|
||||
extraHeaders = headers
|
||||
case let .SessionDelegate(delegate):
|
||||
sessionDelegate = delegate
|
||||
case let .ForcePolling(force):
|
||||
forcePolling = force
|
||||
case let .ForceWebsockets(force):
|
||||
forceWebsockets = force
|
||||
case let .Cookies(cookies):
|
||||
self.cookies = cookies
|
||||
case let .Path(path):
|
||||
socketPath = path
|
||||
case let .ExtraHeaders(headers):
|
||||
extraHeaders = headers
|
||||
case let .VoipEnabled(enable):
|
||||
voipEnabled = enable
|
||||
case let .Secure(secure):
|
||||
self.secure = secure
|
||||
case let .Security(security):
|
||||
self.security = security
|
||||
case let .SelfSigned(selfSigned):
|
||||
self.selfSigned = selfSigned
|
||||
default:
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
super.init()
|
||||
|
||||
(urlPolling, urlWebSocket) = createURLs()
|
||||
}
|
||||
|
||||
public convenience init(client: SocketEngineClient, url: String, options: NSDictionary?) {
|
||||
self.init(client: client, url: url,
|
||||
options: options?.toSocketOptionsSet() ?? [])
|
||||
public convenience init(client: SocketEngineClient, url: NSURL, options: NSDictionary?) {
|
||||
self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? [])
|
||||
}
|
||||
|
||||
|
||||
deinit {
|
||||
DefaultSocketLogger.Logger.log("Engine is being deinit", type: logType)
|
||||
DefaultSocketLogger.Logger.log("Engine is being released", type: logType)
|
||||
closed = true
|
||||
stopPolling()
|
||||
}
|
||||
@@ -123,26 +135,19 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
allowLossyConversion: false) else { return }
|
||||
|
||||
do {
|
||||
if let dict = try NSJSONSerialization.JSONObjectWithData(stringData,
|
||||
options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
|
||||
guard let code = dict["code"] as? Int else { return }
|
||||
guard let error = dict["message"] as? String else { return }
|
||||
|
||||
switch code {
|
||||
case 0: // Unknown transport
|
||||
didError(error)
|
||||
case 1: // Unknown sid. clear and retry connect
|
||||
didError(error)
|
||||
case 2: // Bad handshake request
|
||||
didError(error)
|
||||
case 3: // Bad request
|
||||
didError(error)
|
||||
default:
|
||||
didError(error)
|
||||
}
|
||||
if let dict = try NSJSONSerialization.JSONObjectWithData(stringData, options: .MutableContainers) as? NSDictionary {
|
||||
guard let error = dict["message"] as? String else { return }
|
||||
|
||||
/*
|
||||
0: Unknown transport
|
||||
1: Unknown sid
|
||||
2: Bad handshake request
|
||||
3: Bad request
|
||||
*/
|
||||
didError(error)
|
||||
}
|
||||
} catch {
|
||||
didError("Got unknown error from server \(msg)")
|
||||
client?.engineDidError("Got unknown error from server \(msg)")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,9 +156,8 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
// binary in base64 string
|
||||
let noPrefix = message[message.startIndex.advancedBy(2)..<message.endIndex]
|
||||
|
||||
if let data = NSData(base64EncodedString: noPrefix,
|
||||
options: .IgnoreUnknownCharacters) {
|
||||
client?.parseEngineBinaryData(data)
|
||||
if let data = NSData(base64EncodedString: noPrefix, options: .IgnoreUnknownCharacters) {
|
||||
client?.parseEngineBinaryData(data)
|
||||
}
|
||||
|
||||
return true
|
||||
@@ -161,76 +165,92 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
public func close(reason: String) {
|
||||
func postSendClose(data: NSData?, _ res: NSURLResponse?, _ err: NSError?) {
|
||||
sid = ""
|
||||
closed = true
|
||||
invalidated = true
|
||||
connected = false
|
||||
|
||||
pingTimer?.invalidate()
|
||||
ws?.disconnect()
|
||||
stopPolling()
|
||||
client?.engineDidClose(reason)
|
||||
|
||||
private func closeOutEngine(reason: String) {
|
||||
sid = ""
|
||||
closed = true
|
||||
invalidated = true
|
||||
connected = false
|
||||
|
||||
ws?.disconnect()
|
||||
stopPolling()
|
||||
client?.engineDidClose(reason)
|
||||
}
|
||||
|
||||
/// Starts the connection to the server
|
||||
public func connect() {
|
||||
if connected {
|
||||
DefaultSocketLogger.Logger.error("Engine tried opening while connected. Assuming this was a reconnect", type: logType)
|
||||
disconnect("reconnect")
|
||||
}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
|
||||
DefaultSocketLogger.Logger.log("Starting engine. Server: %@", type: logType, args: url)
|
||||
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
|
||||
|
||||
if websocket {
|
||||
sendWebSocketMessage("", withType: .Close, withData: [])
|
||||
postSendClose(nil, nil, nil)
|
||||
} else {
|
||||
// We need to take special care when we're polling that we send it ASAP
|
||||
postWait.append(String(SocketEnginePacketType.Close.rawValue))
|
||||
let req = createRequestForPostWithPostWait()
|
||||
doRequest(req, withCallback: postSendClose)
|
||||
resetEngine()
|
||||
|
||||
if forceWebsockets {
|
||||
polling = false
|
||||
websocket = true
|
||||
createWebsocketAndConnect()
|
||||
return
|
||||
}
|
||||
|
||||
let reqPolling = NSMutableURLRequest(URL: urlPolling)
|
||||
|
||||
if cookies != nil {
|
||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
|
||||
reqPolling.allHTTPHeaderFields = headers
|
||||
}
|
||||
|
||||
if let extraHeaders = extraHeaders {
|
||||
for (headerName, value) in extraHeaders {
|
||||
reqPolling.setValue(value, forHTTPHeaderField: headerName)
|
||||
}
|
||||
}
|
||||
|
||||
dispatch_async(emitQueue) {
|
||||
self.doLongPoll(reqPolling)
|
||||
}
|
||||
}
|
||||
|
||||
private func createURLs(params: [String: AnyObject]?) -> (String, String) {
|
||||
private func createURLs() -> (NSURL, NSURL) {
|
||||
if client == nil {
|
||||
return ("", "")
|
||||
return (NSURL(), NSURL())
|
||||
}
|
||||
|
||||
let socketURL = "\(url)\(socketPath)/?transport="
|
||||
var urlPolling: String
|
||||
var urlWebSocket: String
|
||||
let urlPolling = NSURLComponents(string: url.absoluteString)!
|
||||
let urlWebSocket = NSURLComponents(string: url.absoluteString)!
|
||||
var queryString = ""
|
||||
|
||||
urlWebSocket.path = socketPath
|
||||
urlPolling.path = socketPath
|
||||
|
||||
if secure {
|
||||
urlPolling = "https://" + socketURL + "polling"
|
||||
urlWebSocket = "wss://" + socketURL + "websocket"
|
||||
urlPolling.scheme = "https"
|
||||
urlWebSocket.scheme = "wss"
|
||||
} else {
|
||||
urlPolling = "http://" + socketURL + "polling"
|
||||
urlWebSocket = "ws://" + socketURL + "websocket"
|
||||
urlPolling.scheme = "http"
|
||||
urlWebSocket.scheme = "ws"
|
||||
}
|
||||
|
||||
if params != nil {
|
||||
for (key, value) in params! {
|
||||
let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters(
|
||||
allowedCharacterSet)!
|
||||
urlPolling += "&\(keyEsc)="
|
||||
urlWebSocket += "&\(keyEsc)="
|
||||
if connectParams != nil {
|
||||
for (key, value) in connectParams! {
|
||||
let keyEsc = key.urlEncode()!
|
||||
let valueEsc = "\(value)".urlEncode()!
|
||||
|
||||
if value is String {
|
||||
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
|
||||
allowedCharacterSet)!
|
||||
urlPolling += "\(valueEsc)"
|
||||
urlWebSocket += "\(valueEsc)"
|
||||
} else {
|
||||
urlPolling += "\(value)"
|
||||
urlWebSocket += "\(value)"
|
||||
}
|
||||
queryString += "&\(keyEsc)=\(valueEsc)"
|
||||
}
|
||||
}
|
||||
|
||||
return (urlPolling, urlWebSocket)
|
||||
urlWebSocket.percentEncodedQuery = "transport=websocket" + queryString
|
||||
urlPolling.percentEncodedQuery = "transport=polling&b64=1" + queryString
|
||||
|
||||
return (urlPolling.URL!, urlWebSocket.URL!)
|
||||
}
|
||||
|
||||
private func createWebsocketAndConnect() {
|
||||
let wsUrl = urlWebSocket + (sid == "" ? "" : "&sid=\(sid)")
|
||||
|
||||
ws = WebSocket(url: NSURL(string: wsUrl)!)
|
||||
ws = WebSocket(url: urlWebSocketWithSid)
|
||||
|
||||
if cookies != nil {
|
||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
|
||||
@@ -249,14 +269,43 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
ws?.voipEnabled = voipEnabled
|
||||
ws?.delegate = self
|
||||
ws?.selfSignedSSL = selfSigned
|
||||
ws?.security = security
|
||||
|
||||
ws?.connect()
|
||||
}
|
||||
|
||||
public func didError(error: String) {
|
||||
DefaultSocketLogger.Logger.error(error, type: logType)
|
||||
DefaultSocketLogger.Logger.error("%@", type: logType, args: error)
|
||||
client?.engineDidError(error)
|
||||
close(error)
|
||||
disconnect(error)
|
||||
}
|
||||
|
||||
public func disconnect(reason: String) {
|
||||
guard connected else { return closeOutEngine(reason) }
|
||||
|
||||
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
|
||||
|
||||
if closed {
|
||||
return closeOutEngine(reason)
|
||||
}
|
||||
|
||||
if websocket {
|
||||
sendWebSocketMessage("", withType: .Close, withData: [])
|
||||
closeOutEngine(reason)
|
||||
} else {
|
||||
disconnectPolling(reason)
|
||||
}
|
||||
}
|
||||
|
||||
// We need to take special care when we're polling that we send it ASAP
|
||||
// Also make sure we're on the emitQueue since we're touching postWait
|
||||
private func disconnectPolling(reason: String) {
|
||||
dispatch_sync(emitQueue) {
|
||||
self.postWait.append(String(SocketEnginePacketType.Close.rawValue))
|
||||
let req = self.createRequestForPostWithPostWait()
|
||||
self.doRequest(req) {_, _, _ in }
|
||||
self.closeOutEngine(reason)
|
||||
}
|
||||
}
|
||||
|
||||
public func doFastUpgrade() {
|
||||
@@ -295,7 +344,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
guard let ws = self.ws else { return }
|
||||
|
||||
for msg in postWait {
|
||||
ws.writeString(fixDoubleUTF8(msg))
|
||||
ws.writeString(msg)
|
||||
}
|
||||
|
||||
postWait.removeAll(keepCapacity: true)
|
||||
@@ -339,18 +388,16 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
createWebsocketAndConnect()
|
||||
}
|
||||
|
||||
|
||||
startPingTimer()
|
||||
sendPing()
|
||||
|
||||
if !forceWebsockets {
|
||||
doPoll()
|
||||
}
|
||||
|
||||
client?.engineDidOpen?("Connect")
|
||||
client?.engineDidOpen("Connect")
|
||||
}
|
||||
} catch {
|
||||
didError("Error parsing open packet")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -362,46 +409,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
upgradeTransport()
|
||||
}
|
||||
}
|
||||
|
||||
public func open(opts: [String: AnyObject]?) {
|
||||
if connected {
|
||||
DefaultSocketLogger.Logger.error("Engine tried opening while connected. This is probably a programming error. "
|
||||
+ "Abandoning open attempt", type: logType)
|
||||
return
|
||||
}
|
||||
|
||||
connectParams = opts
|
||||
|
||||
DefaultSocketLogger.Logger.log("Starting engine", type: logType)
|
||||
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
|
||||
|
||||
resetEngine()
|
||||
|
||||
(urlPolling, urlWebSocket) = createURLs(opts)
|
||||
|
||||
if forceWebsockets {
|
||||
polling = false
|
||||
websocket = true
|
||||
createWebsocketAndConnect()
|
||||
return
|
||||
}
|
||||
|
||||
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
|
||||
|
||||
if cookies != nil {
|
||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
|
||||
reqPolling.allHTTPHeaderFields = headers
|
||||
}
|
||||
|
||||
if let extraHeaders = extraHeaders {
|
||||
for (headerName, value) in extraHeaders {
|
||||
reqPolling.setValue(value, forHTTPHeaderField: headerName)
|
||||
}
|
||||
}
|
||||
|
||||
doLongPoll(reqPolling)
|
||||
}
|
||||
|
||||
|
||||
public func parseEngineData(data: NSData) {
|
||||
DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data)
|
||||
client?.parseEngineBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
|
||||
@@ -421,7 +429,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
return
|
||||
}
|
||||
|
||||
if fromPolling && type != .Noop {
|
||||
if fromPolling && type != .Noop && doubleEncodeUTF8 {
|
||||
fixedString = fixDoubleUTF8(message)
|
||||
} else {
|
||||
fixedString = message
|
||||
@@ -443,6 +451,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
}
|
||||
}
|
||||
|
||||
// Puts the engine back in its default state
|
||||
private func resetEngine() {
|
||||
closed = false
|
||||
connected = false
|
||||
@@ -458,41 +467,30 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
waitingForPost = false
|
||||
websocket = false
|
||||
}
|
||||
|
||||
/// Send an engine message (4)
|
||||
public func send(msg: String, withData datas: [NSData]) {
|
||||
if probing {
|
||||
probeWait.append((msg, .Message, datas))
|
||||
} else {
|
||||
write(msg, withType: .Message, withData: datas)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func sendPing() {
|
||||
private func sendPing() {
|
||||
if !connected {
|
||||
return
|
||||
}
|
||||
|
||||
//Server is not responding
|
||||
if pongsMissed > pongsMissedMax {
|
||||
pingTimer?.invalidate()
|
||||
client?.engineDidClose("Ping timeout")
|
||||
return
|
||||
}
|
||||
|
||||
pongsMissed += 1
|
||||
write("", withType: .Ping, withData: [])
|
||||
}
|
||||
|
||||
// Starts the ping timer
|
||||
private func startPingTimer() {
|
||||
|
||||
if let pingInterval = pingInterval {
|
||||
pingTimer?.invalidate()
|
||||
pingTimer = nil
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self,
|
||||
selector: Selector("sendPing"), userInfo: nil, repeats: true)
|
||||
pongsMissed += 1
|
||||
write("", withType: .Ping, withData: [])
|
||||
|
||||
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(pingInterval * Double(NSEC_PER_SEC)))
|
||||
dispatch_after(time, dispatch_get_main_queue()) {[weak self] in
|
||||
self?.sendPing()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Moves from long-polling to websockets
|
||||
private func upgradeTransport() {
|
||||
if ws?.isConnected ?? false {
|
||||
DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: logType)
|
||||
@@ -503,9 +501,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Write a message, independent of transport.
|
||||
*/
|
||||
/// Write a message, independent of transport.
|
||||
public func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData]) {
|
||||
dispatch_async(emitQueue) {
|
||||
guard self.connected else { return }
|
||||
@@ -514,10 +510,12 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
DefaultSocketLogger.Logger.log("Writing ws: %@ has data: %@",
|
||||
type: self.logType, args: msg, data.count != 0)
|
||||
self.sendWebSocketMessage(msg, withType: type, withData: data)
|
||||
} else {
|
||||
} else if !self.probing {
|
||||
DefaultSocketLogger.Logger.log("Writing poll: %@ has data: %@",
|
||||
type: self.logType, args: msg, data.count != 0)
|
||||
self.sendPollMessage(msg, withType: type, withData: data)
|
||||
} else {
|
||||
self.probeWait.append((msg, type, data))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -543,17 +541,14 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
}
|
||||
|
||||
if websocket {
|
||||
pingTimer?.invalidate()
|
||||
connected = false
|
||||
websocket = false
|
||||
|
||||
let reason = error?.localizedDescription ?? "Socket Disconnected"
|
||||
|
||||
if error != nil {
|
||||
if let reason = error?.localizedDescription {
|
||||
didError(reason)
|
||||
} else {
|
||||
client?.engineDidClose("Socket Disconnected")
|
||||
}
|
||||
|
||||
client?.engineDidClose(reason)
|
||||
} else {
|
||||
flushProbeWait()
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ import Foundation
|
||||
@objc public protocol SocketEngineClient {
|
||||
func engineDidError(reason: String)
|
||||
func engineDidClose(reason: String)
|
||||
optional func engineDidOpen(reason: String)
|
||||
func engineDidOpen(reason: String)
|
||||
func parseEngineMessage(msg: String)
|
||||
func parseEngineBinaryData(data: NSData)
|
||||
}
|
||||
@@ -25,6 +25,6 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
@objc public enum SocketEnginePacketType: Int {
|
||||
@objc public enum SocketEnginePacketType : Int {
|
||||
case Open, Close, Ping, Pong, Message, Upgrade, Noop
|
||||
}
|
||||
@@ -25,7 +25,7 @@
|
||||
import Foundation
|
||||
|
||||
/// Protocol that is used to implement socket.io polling support
|
||||
public protocol SocketEnginePollable: SocketEngineSpec {
|
||||
public protocol SocketEnginePollable : SocketEngineSpec {
|
||||
var invalidated: Bool { get }
|
||||
/// Holds strings waiting to be sent over polling.
|
||||
/// You shouldn't need to mess with this.
|
||||
@@ -71,7 +71,7 @@ extension SocketEnginePollable {
|
||||
|
||||
postWait.removeAll(keepCapacity: false)
|
||||
|
||||
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&sid=\(sid)")!)
|
||||
let req = NSMutableURLRequest(URL: urlPollingWithSid)
|
||||
|
||||
addHeaders(req)
|
||||
|
||||
@@ -93,26 +93,26 @@ extension SocketEnginePollable {
|
||||
}
|
||||
|
||||
waitingForPoll = true
|
||||
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&sid=\(sid)&b64=1")!)
|
||||
let req = NSMutableURLRequest(URL: urlPollingWithSid)
|
||||
|
||||
addHeaders(req)
|
||||
doLongPoll(req)
|
||||
}
|
||||
|
||||
func doRequest(req: NSURLRequest, withCallback callback: (NSData?, NSURLResponse?, NSError?) -> Void) {
|
||||
if !polling || closed || invalidated {
|
||||
DefaultSocketLogger.Logger.error("Tried to do polling request when not supposed to", type: "SocketEnginePolling")
|
||||
return
|
||||
}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling")
|
||||
|
||||
session?.dataTaskWithRequest(req, completionHandler: callback).resume()
|
||||
if !polling || closed || invalidated || fastUpgrade {
|
||||
DefaultSocketLogger.Logger.error("Tried to do polling request when not supposed to", type: "SocketEnginePolling")
|
||||
return
|
||||
}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling")
|
||||
|
||||
session?.dataTaskWithRequest(req, completionHandler: callback).resume()
|
||||
}
|
||||
|
||||
func doLongPoll(req: NSURLRequest) {
|
||||
doRequest(req) {[weak self] data, res, err in
|
||||
guard let this = self else {return}
|
||||
guard let this = self where this.polling else { return }
|
||||
|
||||
if err != nil || data == nil {
|
||||
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
|
||||
@@ -181,9 +181,7 @@ extension SocketEnginePollable {
|
||||
}
|
||||
|
||||
func parsePollingMessage(str: String) {
|
||||
guard str.characters.count != 1 else {
|
||||
return
|
||||
}
|
||||
guard str.characters.count != 1 else { return }
|
||||
|
||||
var reader = SocketStringReader(message: str)
|
||||
|
||||
@@ -206,21 +204,26 @@ extension SocketEnginePollable {
|
||||
/// Send polling message.
|
||||
/// Only call on emitQueue
|
||||
public func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData]) {
|
||||
DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue)
|
||||
let fixedMessage = doubleEncodeUTF8(message)
|
||||
let strMsg = "\(type.rawValue)\(fixedMessage)"
|
||||
|
||||
postWait.append(strMsg)
|
||||
|
||||
for data in datas {
|
||||
if case let .Right(bin) = createBinaryDataForSend(data) {
|
||||
postWait.append(bin)
|
||||
}
|
||||
}
|
||||
|
||||
if !waitingForPost {
|
||||
flushWaitingForPost()
|
||||
DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue)
|
||||
let fixedMessage: String
|
||||
|
||||
if doubleEncodeUTF8 {
|
||||
fixedMessage = doubleEncodeUTF8(message)
|
||||
} else {
|
||||
fixedMessage = message
|
||||
}
|
||||
|
||||
postWait.append(String(type.rawValue) + fixedMessage)
|
||||
|
||||
for data in datas {
|
||||
if case let .Right(bin) = createBinaryDataForSend(data) {
|
||||
postWait.append(bin)
|
||||
}
|
||||
}
|
||||
|
||||
if !waitingForPost {
|
||||
flushWaitingForPost()
|
||||
}
|
||||
}
|
||||
|
||||
public func stopPolling() {
|
||||
|
||||
@@ -29,37 +29,52 @@ import Foundation
|
||||
weak var client: SocketEngineClient? { get set }
|
||||
var closed: Bool { get }
|
||||
var connected: Bool { get }
|
||||
var connectParams: [String: AnyObject]? { get set }
|
||||
var doubleEncodeUTF8: Bool { get }
|
||||
var cookies: [NSHTTPCookie]? { get }
|
||||
var extraHeaders: [String: String]? { get }
|
||||
var fastUpgrade: Bool { get }
|
||||
var forcePolling: Bool { get }
|
||||
var forceWebsockets: Bool { get }
|
||||
var parseQueue: dispatch_queue_t! { get }
|
||||
var pingTimer: NSTimer? { get }
|
||||
var polling: Bool { get }
|
||||
var probing: Bool { get }
|
||||
var emitQueue: dispatch_queue_t! { get }
|
||||
var handleQueue: dispatch_queue_t! { get }
|
||||
var sid: String { get }
|
||||
var socketPath: String { get }
|
||||
var urlPolling: String { get }
|
||||
var urlWebSocket: String { get }
|
||||
var urlPolling: NSURL { get }
|
||||
var urlWebSocket: NSURL { get }
|
||||
var websocket: Bool { get }
|
||||
var ws: WebSocket? { get }
|
||||
|
||||
init(client: SocketEngineClient, url: String, options: NSDictionary?)
|
||||
init(client: SocketEngineClient, url: NSURL, options: NSDictionary?)
|
||||
|
||||
func close(reason: String)
|
||||
func connect()
|
||||
func didError(error: String)
|
||||
func disconnect(reason: String)
|
||||
func doFastUpgrade()
|
||||
func flushWaitingForPostToWebSocket()
|
||||
func open(opts: [String: AnyObject]?)
|
||||
func parseEngineData(data: NSData)
|
||||
func parseEngineMessage(message: String, fromPolling: Bool)
|
||||
func send(msg: String, withData datas: [NSData])
|
||||
func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData])
|
||||
}
|
||||
|
||||
extension SocketEngineSpec {
|
||||
var urlPollingWithSid: NSURL {
|
||||
let com = NSURLComponents(URL: urlPolling, resolvingAgainstBaseURL: false)!
|
||||
com.percentEncodedQuery = com.percentEncodedQuery! + "&sid=\(sid.urlEncode()!)"
|
||||
|
||||
return com.URL!
|
||||
}
|
||||
|
||||
var urlWebSocketWithSid: NSURL {
|
||||
let com = NSURLComponents(URL: urlWebSocket, resolvingAgainstBaseURL: false)!
|
||||
com.percentEncodedQuery = com.percentEncodedQuery! + (sid == "" ? "" : "&sid=\(sid.urlEncode()!)")
|
||||
|
||||
return com.URL!
|
||||
}
|
||||
|
||||
func createBinaryDataForSend(data: NSData) -> Either<NSData, String> {
|
||||
if websocket {
|
||||
var byteArray = [UInt8](count: 1, repeatedValue: 0x4)
|
||||
@@ -69,9 +84,32 @@ extension SocketEngineSpec {
|
||||
|
||||
return .Left(mutData)
|
||||
} else {
|
||||
let str = "b4" + data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
|
||||
let str = "b4" + data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
|
||||
|
||||
return .Right(str)
|
||||
}
|
||||
}
|
||||
|
||||
func doubleEncodeUTF8(string: String) -> String {
|
||||
if let latin1 = string.dataUsingEncoding(NSUTF8StringEncoding),
|
||||
utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding) {
|
||||
return utf8 as String
|
||||
} else {
|
||||
return string
|
||||
}
|
||||
}
|
||||
|
||||
func fixDoubleUTF8(string: String) -> String {
|
||||
if let utf8 = string.dataUsingEncoding(NSISOLatin1StringEncoding),
|
||||
latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding) {
|
||||
return latin1 as String
|
||||
} else {
|
||||
return string
|
||||
}
|
||||
}
|
||||
|
||||
/// Send an engine message (4)
|
||||
func send(msg: String, withData datas: [NSData]) {
|
||||
write(msg, withType: .Message, withData: datas)
|
||||
}
|
||||
}
|
||||
@@ -26,9 +26,7 @@
|
||||
import Foundation
|
||||
|
||||
/// Protocol that is used to implement socket.io WebSocket support
|
||||
public protocol SocketEngineWebsocket: SocketEngineSpec, WebSocketDelegate {
|
||||
var ws: WebSocket? { get }
|
||||
|
||||
public protocol SocketEngineWebsocket : SocketEngineSpec, WebSocketDelegate {
|
||||
func sendWebSocketMessage(str: String, withType type: SocketEnginePacketType, withData datas: [NSData])
|
||||
}
|
||||
|
||||
|
||||
+114
-172
@@ -24,20 +24,29 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable {
|
||||
public let socketURL: String
|
||||
public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable {
|
||||
public let socketURL: NSURL
|
||||
|
||||
public private(set) var engine: SocketEngineSpec?
|
||||
public private(set) var status = SocketIOClientStatus.NotConnected
|
||||
public private(set) var status = SocketIOClientStatus.NotConnected {
|
||||
didSet {
|
||||
switch status {
|
||||
case .Connected:
|
||||
reconnecting = false
|
||||
currentReconnectAttempt = 0
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public var connectParams: [String: AnyObject]?
|
||||
public var forceNew = false
|
||||
public var nsp = "/"
|
||||
public var options: Set<SocketIOClientOption>
|
||||
public var reconnects = true
|
||||
public var reconnectWait = 10
|
||||
public var sid: String? {
|
||||
return engine?.sid
|
||||
return nsp + "#" + (engine?.sid ?? "")
|
||||
}
|
||||
|
||||
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
@@ -47,31 +56,26 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
private var anyHandler: ((SocketAnyEvent) -> Void)?
|
||||
private var currentReconnectAttempt = 0
|
||||
private var handlers = [SocketEventHandler]()
|
||||
private var reconnectTimer: NSTimer?
|
||||
private var ackHandlers = SocketAckManager()
|
||||
private var reconnecting = false
|
||||
|
||||
private(set) var currentAck = -1
|
||||
private(set) var handleQueue = dispatch_get_main_queue()
|
||||
private(set) var reconnectAttempts = -1
|
||||
|
||||
var waitingData = [SocketPacket]()
|
||||
|
||||
/**
|
||||
Type safe way to create a new SocketIOClient. opts can be omitted
|
||||
*/
|
||||
public init(socketURL: String, options: Set<SocketIOClientOption> = []) {
|
||||
var waitingPackets = [SocketPacket]()
|
||||
|
||||
/// Type safe way to create a new SocketIOClient. opts can be omitted
|
||||
public init(socketURL: NSURL, options: Set<SocketIOClientOption> = []) {
|
||||
self.options = options
|
||||
|
||||
if socketURL["https://"].matches().count != 0 {
|
||||
self.socketURL = socketURL
|
||||
|
||||
if socketURL.absoluteString.hasPrefix("https://") {
|
||||
self.options.insertIgnore(.Secure(true))
|
||||
}
|
||||
|
||||
self.socketURL = socketURL["https?://"] <~ ""
|
||||
|
||||
|
||||
for option in options {
|
||||
switch option {
|
||||
case let .ConnectParams(params):
|
||||
connectParams = params
|
||||
case let .Reconnects(reconnects):
|
||||
self.reconnects = reconnects
|
||||
case let .ReconnectAttempts(attempts):
|
||||
@@ -92,24 +96,21 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
self.options.insertIgnore(.Path("/socket.io"))
|
||||
|
||||
|
||||
self.options.insertIgnore(.Path("/socket.io/"))
|
||||
|
||||
super.init()
|
||||
}
|
||||
|
||||
/**
|
||||
Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity.
|
||||
If using Swift it's recommended to use `init(var socketURL: String, options: Set<SocketIOClientOption>)`
|
||||
*/
|
||||
public convenience init(socketURL: String, options: NSDictionary?) {
|
||||
self.init(socketURL: socketURL,
|
||||
options: options?.toSocketOptionsSet() ?? [])
|
||||
|
||||
/// Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity.
|
||||
/// If using Swift it's recommended to use `init(socketURL: NSURL, options: Set<SocketIOClientOption>)`
|
||||
public convenience init(socketURL: NSURL, options: NSDictionary?) {
|
||||
self.init(socketURL: socketURL, options: options?.toSocketOptionsSet() ?? [])
|
||||
}
|
||||
|
||||
deinit {
|
||||
DefaultSocketLogger.Logger.log("Client is being deinit", type: logType)
|
||||
engine?.close("Client Deinit")
|
||||
DefaultSocketLogger.Logger.log("Client is being released", type: logType)
|
||||
engine?.disconnect("Client Deinit")
|
||||
}
|
||||
|
||||
private func addEngine() -> SocketEngineSpec {
|
||||
@@ -120,51 +121,36 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
return engine!
|
||||
}
|
||||
|
||||
private func clearReconnectTimer() {
|
||||
reconnectTimer?.invalidate()
|
||||
reconnectTimer = nil
|
||||
}
|
||||
|
||||
@available(*, deprecated=6.0)
|
||||
public func close() {
|
||||
disconnect()
|
||||
}
|
||||
|
||||
/**
|
||||
Connect to the server.
|
||||
*/
|
||||
/// Connect to the server.
|
||||
public func connect() {
|
||||
connect(timeoutAfter: 0, withTimeoutHandler: nil)
|
||||
}
|
||||
|
||||
/**
|
||||
Connect to the server. If we aren't connected after timeoutAfter, call handler
|
||||
*/
|
||||
/// Connect to the server. If we aren't connected after timeoutAfter, call handler
|
||||
public func connect(timeoutAfter timeoutAfter: Int, withTimeoutHandler handler: (() -> Void)?) {
|
||||
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
|
||||
|
||||
guard status != .Connected else {
|
||||
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket",
|
||||
type: logType)
|
||||
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket", type: logType)
|
||||
return
|
||||
}
|
||||
|
||||
status = .Connecting
|
||||
|
||||
if engine == nil || forceNew {
|
||||
addEngine().open(connectParams)
|
||||
addEngine().connect()
|
||||
} else {
|
||||
engine?.open(connectParams)
|
||||
engine?.connect()
|
||||
}
|
||||
|
||||
|
||||
guard timeoutAfter != 0 else { return }
|
||||
|
||||
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
|
||||
|
||||
dispatch_after(time, handleQueue) {[weak self] in
|
||||
if let this = self where this.status != .Connected {
|
||||
this.status = .Closed
|
||||
this.engine?.close("Connect timeout")
|
||||
if let this = self where this.status != .Connected && this.status != .Disconnected {
|
||||
this.status = .Disconnected
|
||||
this.engine?.disconnect("Connect timeout")
|
||||
|
||||
handler?()
|
||||
}
|
||||
@@ -177,10 +163,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
return {[weak self, ack = currentAck] timeout, callback in
|
||||
if let this = self {
|
||||
this.ackHandlers.addAck(ack, callback: callback)
|
||||
|
||||
dispatch_async(this.emitQueue) {
|
||||
this._emit(items, ack: ack)
|
||||
}
|
||||
this._emit(items, ack: ack)
|
||||
|
||||
if timeout != 0 {
|
||||
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
|
||||
@@ -196,8 +179,6 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
func didConnect() {
|
||||
DefaultSocketLogger.Logger.log("Socket connected", type: logType)
|
||||
status = .Connected
|
||||
currentReconnectAttempt = 0
|
||||
clearReconnectTimer()
|
||||
|
||||
// Don't handle as internal because something crazy could happen where
|
||||
// we disconnect before it's handled
|
||||
@@ -205,79 +186,66 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
}
|
||||
|
||||
func didDisconnect(reason: String) {
|
||||
guard status != .Closed else {
|
||||
return
|
||||
}
|
||||
guard status != .Disconnected else { return }
|
||||
|
||||
DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason)
|
||||
|
||||
status = .Closed
|
||||
reconnects = false
|
||||
status = .Disconnected
|
||||
|
||||
// Make sure the engine is actually dead.
|
||||
engine?.close(reason)
|
||||
engine?.disconnect(reason)
|
||||
handleEvent("disconnect", data: [reason], isInternalMessage: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Disconnects the socket. Only reconnect the same socket if you know what you're doing.
|
||||
Will turn off automatic reconnects.
|
||||
*/
|
||||
/// Disconnects the socket.
|
||||
public func disconnect() {
|
||||
assert(status != .NotConnected, "Tried closing a NotConnected client")
|
||||
|
||||
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
|
||||
|
||||
reconnects = false
|
||||
didDisconnect("Disconnect")
|
||||
}
|
||||
|
||||
/**
|
||||
Send a message to the server
|
||||
*/
|
||||
/// Send a message to the server
|
||||
public func emit(event: String, _ items: AnyObject...) {
|
||||
emit(event, withItems: items)
|
||||
}
|
||||
|
||||
/**
|
||||
Same as emit, but meant for Objective-C
|
||||
*/
|
||||
/// Same as emit, but meant for Objective-C
|
||||
public func emit(event: String, withItems items: [AnyObject]) {
|
||||
guard status == .Connected else {
|
||||
handleEvent("error", data: ["Tried emitting \(event) when not connected"], isInternalMessage: true)
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(emitQueue) {
|
||||
self._emit([event] + items)
|
||||
}
|
||||
|
||||
_emit([event] + items)
|
||||
}
|
||||
|
||||
/**
|
||||
Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
|
||||
an ack.
|
||||
*/
|
||||
/// Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
|
||||
/// an ack.
|
||||
public func emitWithAck(event: String, _ items: AnyObject...) -> OnAckCallback {
|
||||
return emitWithAck(event, withItems: items)
|
||||
}
|
||||
|
||||
/**
|
||||
Same as emitWithAck, but for Objective-C
|
||||
*/
|
||||
/// Same as emitWithAck, but for Objective-C
|
||||
public func emitWithAck(event: String, withItems items: [AnyObject]) -> OnAckCallback {
|
||||
return createOnAck([event] + items)
|
||||
}
|
||||
|
||||
private func _emit(data: [AnyObject], ack: Int? = nil) {
|
||||
guard status == .Connected else {
|
||||
handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
|
||||
return
|
||||
dispatch_async(emitQueue) {
|
||||
guard self.status == .Connected else {
|
||||
self.handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
|
||||
return
|
||||
}
|
||||
|
||||
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: self.nsp, ack: false)
|
||||
let str = packet.packetString
|
||||
|
||||
DefaultSocketLogger.Logger.log("Emitting: %@", type: self.logType, args: str)
|
||||
|
||||
self.engine?.send(str, withData: packet.binary)
|
||||
}
|
||||
|
||||
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
|
||||
let str = packet.packetString
|
||||
|
||||
DefaultSocketLogger.Logger.log("Emitting: %@", type: logType, args: str)
|
||||
|
||||
engine?.send(str, withData: packet.binary)
|
||||
}
|
||||
|
||||
// If the server wants to know that the client received data
|
||||
@@ -295,14 +263,17 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
}
|
||||
|
||||
public func engineDidClose(reason: String) {
|
||||
waitingData.removeAll()
|
||||
waitingPackets.removeAll()
|
||||
|
||||
if status != .Disconnected {
|
||||
status = .NotConnected
|
||||
}
|
||||
|
||||
if status == .Closed || !reconnects {
|
||||
if status == .Disconnected || !reconnects {
|
||||
didDisconnect(reason)
|
||||
} else if status != .Reconnecting {
|
||||
status = .Reconnecting
|
||||
handleEvent("reconnect", data: [reason], isInternalMessage: true)
|
||||
tryReconnect()
|
||||
} else if !reconnecting {
|
||||
reconnecting = true
|
||||
tryReconnectWithReason(reason)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,23 +283,23 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
|
||||
handleEvent("error", data: [reason], isInternalMessage: true)
|
||||
}
|
||||
|
||||
public func engineDidOpen(reason: String) {
|
||||
DefaultSocketLogger.Logger.log(reason, type: "SocketEngineClient")
|
||||
}
|
||||
|
||||
// Called when the socket gets an ack for something it sent
|
||||
func handleAck(ack: Int, data: [AnyObject]) {
|
||||
guard status == .Connected else {return}
|
||||
guard status == .Connected else { return }
|
||||
|
||||
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
|
||||
|
||||
ackHandlers.executeAck(ack, items: data)
|
||||
}
|
||||
|
||||
/**
|
||||
Causes an event to be handled. Only use if you know what you're doing.
|
||||
*/
|
||||
/// Causes an event to be handled. Only use if you know what you're doing.
|
||||
public func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool, withAck ack: Int = -1) {
|
||||
guard status == .Connected || isInternalMessage else {
|
||||
return
|
||||
}
|
||||
guard status == .Connected || isInternalMessage else { return }
|
||||
|
||||
DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data ?? "")
|
||||
|
||||
@@ -341,9 +312,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Leaves nsp and goes back to /
|
||||
*/
|
||||
/// Leaves nsp and goes back to /
|
||||
public func leaveNamespace() {
|
||||
if nsp != "/" {
|
||||
engine?.send("1\(nsp)", withData: [])
|
||||
@@ -351,9 +320,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Joins namespace
|
||||
*/
|
||||
/// Joins namespace
|
||||
public func joinNamespace(namespace: String) {
|
||||
nsp = namespace
|
||||
|
||||
@@ -363,28 +330,22 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Removes handler(s)
|
||||
*/
|
||||
/// Removes handler(s) based on name
|
||||
public func off(event: String) {
|
||||
DefaultSocketLogger.Logger.log("Removing handler for event: %@", type: logType, args: event)
|
||||
|
||||
handlers = handlers.filter { $0.event != event }
|
||||
handlers = handlers.filter({ $0.event != event })
|
||||
}
|
||||
|
||||
/**
|
||||
Removes a handler with the specified UUID gotten from an `on` or `once`
|
||||
*/
|
||||
/// Removes a handler with the specified UUID gotten from an `on` or `once`
|
||||
public func off(id id: NSUUID) {
|
||||
DefaultSocketLogger.Logger.log("Removing handler with id: %@", type: logType, args: id)
|
||||
|
||||
handlers = handlers.filter { $0.id != id }
|
||||
handlers = handlers.filter({ $0.id != id })
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler for an event.
|
||||
Returns: A unique id for the handler
|
||||
*/
|
||||
/// Adds a handler for an event.
|
||||
/// Returns: A unique id for the handler
|
||||
public func on(event: String, callback: NormalCallback) -> NSUUID {
|
||||
DefaultSocketLogger.Logger.log("Adding handler for event: %@", type: logType, args: event)
|
||||
|
||||
@@ -394,17 +355,15 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
return handler.id
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a single-use handler for an event.
|
||||
Returns: A unique id for the handler
|
||||
*/
|
||||
/// Adds a single-use handler for an event.
|
||||
/// Returns: A unique id for the handler
|
||||
public func once(event: String, callback: NormalCallback) -> NSUUID {
|
||||
DefaultSocketLogger.Logger.log("Adding once handler for event: %@", type: logType, args: event)
|
||||
|
||||
let id = NSUUID()
|
||||
|
||||
let handler = SocketEventHandler(event: event, id: id) {[weak self] data, ack in
|
||||
guard let this = self else {return}
|
||||
guard let this = self else { return }
|
||||
this.off(id: id)
|
||||
callback(data, ack)
|
||||
}
|
||||
@@ -414,21 +373,11 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
return handler.id
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler that will be called on every event.
|
||||
*/
|
||||
/// Adds a handler that will be called on every event.
|
||||
public func onAny(handler: (SocketAnyEvent) -> Void) {
|
||||
anyHandler = handler
|
||||
}
|
||||
|
||||
/**
|
||||
Same as connect
|
||||
*/
|
||||
@available(*, deprecated=6.0)
|
||||
public func open() {
|
||||
connect()
|
||||
}
|
||||
|
||||
public func parseEngineMessage(msg: String) {
|
||||
DefaultSocketLogger.Logger.log("Should parse message: %@", type: "SocketIOClient", args: msg)
|
||||
|
||||
@@ -443,46 +392,35 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tries to reconnect to the server.
|
||||
*/
|
||||
/// Tries to reconnect to the server.
|
||||
public func reconnect() {
|
||||
tryReconnect()
|
||||
guard !reconnecting else { return }
|
||||
|
||||
engine?.disconnect("manual reconnect")
|
||||
}
|
||||
|
||||
/**
|
||||
Removes all handlers.
|
||||
Can be used after disconnecting to break any potential remaining retain cycles.
|
||||
*/
|
||||
/// Removes all handlers.
|
||||
/// Can be used after disconnecting to break any potential remaining retain cycles.
|
||||
public func removeAllHandlers() {
|
||||
handlers.removeAll(keepCapacity: false)
|
||||
}
|
||||
|
||||
private func tryReconnect() {
|
||||
if reconnectTimer == nil {
|
||||
private func tryReconnectWithReason(reason: String) {
|
||||
if reconnecting {
|
||||
DefaultSocketLogger.Logger.log("Starting reconnect", type: logType)
|
||||
|
||||
status = .Reconnecting
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
self.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self.reconnectWait),
|
||||
target: self, selector: "_tryReconnect", userInfo: nil, repeats: true)
|
||||
}
|
||||
handleEvent("reconnect", data: [reason], isInternalMessage: true)
|
||||
|
||||
_tryReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func _tryReconnect() {
|
||||
if status == .Connected {
|
||||
clearReconnectTimer()
|
||||
|
||||
private func _tryReconnect() {
|
||||
if !reconnecting {
|
||||
return
|
||||
}
|
||||
|
||||
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
|
||||
clearReconnectTimer()
|
||||
didDisconnect("Reconnect Failed")
|
||||
|
||||
return
|
||||
return didDisconnect("Reconnect Failed")
|
||||
}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType)
|
||||
@@ -491,6 +429,10 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
|
||||
currentReconnectAttempt += 1
|
||||
connect()
|
||||
|
||||
let dispatchAfter = dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(reconnectWait) * NSEC_PER_SEC))
|
||||
|
||||
dispatch_after(dispatchAfter, dispatch_get_main_queue(), _tryReconnect)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,13 +24,14 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol ClientOption: CustomStringConvertible, Hashable {
|
||||
protocol ClientOption : CustomStringConvertible, Hashable {
|
||||
func getSocketIOOptionValue() -> AnyObject
|
||||
}
|
||||
|
||||
public enum SocketIOClientOption: ClientOption {
|
||||
public enum SocketIOClientOption : ClientOption {
|
||||
case ConnectParams([String: AnyObject])
|
||||
case Cookies([NSHTTPCookie])
|
||||
case DoubleEncodeUTF8(Bool)
|
||||
case ExtraHeaders([String: String])
|
||||
case ForceNew(Bool)
|
||||
case ForcePolling(Bool)
|
||||
@@ -44,6 +45,7 @@ public enum SocketIOClientOption: ClientOption {
|
||||
case ReconnectAttempts(Int)
|
||||
case ReconnectWait(Int)
|
||||
case Secure(Bool)
|
||||
case Security(SSLSecurity)
|
||||
case SelfSigned(Bool)
|
||||
case SessionDelegate(NSURLSessionDelegate)
|
||||
case VoipEnabled(Bool)
|
||||
@@ -56,6 +58,8 @@ public enum SocketIOClientOption: ClientOption {
|
||||
description = "connectParams"
|
||||
case .Cookies:
|
||||
description = "cookies"
|
||||
case .DoubleEncodeUTF8:
|
||||
description = "doubleEncodeUTF8"
|
||||
case .ExtraHeaders:
|
||||
description = "extraHeaders"
|
||||
case .ForceNew:
|
||||
@@ -82,6 +86,8 @@ public enum SocketIOClientOption: ClientOption {
|
||||
description = "reconnectWait"
|
||||
case .Secure:
|
||||
description = "secure"
|
||||
case .Security:
|
||||
description = "security"
|
||||
case .SelfSigned:
|
||||
description = "selfSigned"
|
||||
case .SessionDelegate:
|
||||
@@ -105,6 +111,8 @@ public enum SocketIOClientOption: ClientOption {
|
||||
value = params
|
||||
case let .Cookies(cookies):
|
||||
value = cookies
|
||||
case let .DoubleEncodeUTF8(encode):
|
||||
value = encode
|
||||
case let .ExtraHeaders(headers):
|
||||
value = headers
|
||||
case let .ForceNew(force):
|
||||
@@ -131,6 +139,8 @@ public enum SocketIOClientOption: ClientOption {
|
||||
value = wait
|
||||
case let .Secure(secure):
|
||||
value = secure
|
||||
case let .Security(security):
|
||||
value = security
|
||||
case let .SelfSigned(signed):
|
||||
value = signed
|
||||
case let .SessionDelegate(delegate):
|
||||
@@ -147,7 +157,7 @@ public func ==(lhs: SocketIOClientOption, rhs: SocketIOClientOption) -> Bool {
|
||||
return lhs.description == rhs.description
|
||||
}
|
||||
|
||||
extension Set where Element: ClientOption {
|
||||
extension Set where Element : ClientOption {
|
||||
mutating func insertIgnore(element: Element) {
|
||||
if !contains(element) {
|
||||
insert(element)
|
||||
@@ -156,44 +166,48 @@ extension Set where Element: ClientOption {
|
||||
}
|
||||
|
||||
extension NSDictionary {
|
||||
static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
|
||||
private static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
|
||||
switch (key, value) {
|
||||
case let ("connectParams", params as [String: AnyObject]):
|
||||
return .ConnectParams(params)
|
||||
case let ("reconnects", reconnects as Bool):
|
||||
return .Reconnects(reconnects)
|
||||
case let ("reconnectAttempts", attempts as Int):
|
||||
return .ReconnectAttempts(attempts)
|
||||
case let ("reconnectWait", wait as Int):
|
||||
return .ReconnectWait(wait)
|
||||
case let ("cookies", cookies as [NSHTTPCookie]):
|
||||
return .Cookies(cookies)
|
||||
case let ("doubleEncodeUTF8", encode as Bool):
|
||||
return .DoubleEncodeUTF8(encode)
|
||||
case let ("extraHeaders", headers as [String: String]):
|
||||
return .ExtraHeaders(headers)
|
||||
case let ("forceNew", force as Bool):
|
||||
return .ForceNew(force)
|
||||
case let ("forcePolling", force as Bool):
|
||||
return .ForcePolling(force)
|
||||
case let ("forceWebsockets", force as Bool):
|
||||
return .ForceWebsockets(force)
|
||||
case let ("nsp", nsp as String):
|
||||
return .Nsp(nsp)
|
||||
case let ("cookies", cookies as [NSHTTPCookie]):
|
||||
return .Cookies(cookies)
|
||||
case let ("handleQueue", queue as dispatch_queue_t):
|
||||
return .HandleQueue(queue)
|
||||
case let ("log", log as Bool):
|
||||
return .Log(log)
|
||||
case let ("logger", logger as SocketLogger):
|
||||
return .Logger(logger)
|
||||
case let ("sessionDelegate", delegate as NSURLSessionDelegate):
|
||||
return .SessionDelegate(delegate)
|
||||
case let ("nsp", nsp as String):
|
||||
return .Nsp(nsp)
|
||||
case let ("path", path as String):
|
||||
return .Path(path)
|
||||
case let ("extraHeaders", headers as [String: String]):
|
||||
return .ExtraHeaders(headers)
|
||||
case let ("handleQueue", queue as dispatch_queue_t):
|
||||
return .HandleQueue(queue)
|
||||
case let ("voipEnabled", enable as Bool):
|
||||
return .VoipEnabled(enable)
|
||||
case let ("reconnects", reconnects as Bool):
|
||||
return .Reconnects(reconnects)
|
||||
case let ("reconnectAttempts", attempts as Int):
|
||||
return .ReconnectAttempts(attempts)
|
||||
case let ("reconnectWait", wait as Int):
|
||||
return .ReconnectWait(wait)
|
||||
case let ("secure", secure as Bool):
|
||||
return .Secure(secure)
|
||||
case let ("security", security as SSLSecurity):
|
||||
return .Security(security)
|
||||
case let ("selfSigned", selfSigned as Bool):
|
||||
return .SelfSigned(selfSigned)
|
||||
case let ("sessionDelegate", delegate as NSURLSessionDelegate):
|
||||
return .SessionDelegate(delegate)
|
||||
case let ("voipEnabled", enable as Bool):
|
||||
return .VoipEnabled(enable)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//
|
||||
// SocketClientSpec.swift
|
||||
// SocketIOClientSpec.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 1/3/16.
|
||||
@@ -22,9 +22,9 @@
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
protocol SocketClientSpec: class {
|
||||
protocol SocketIOClientSpec : class {
|
||||
var nsp: String { get set }
|
||||
var waitingData: [SocketPacket] { get set }
|
||||
var waitingPackets: [SocketPacket] { get set }
|
||||
|
||||
func didConnect()
|
||||
func didDisconnect(reason: String)
|
||||
@@ -34,7 +34,7 @@ protocol SocketClientSpec: class {
|
||||
func joinNamespace(namespace: String)
|
||||
}
|
||||
|
||||
extension SocketClientSpec {
|
||||
extension SocketIOClientSpec {
|
||||
func didError(reason: String) {
|
||||
DefaultSocketLogger.Logger.error("%@", type: "SocketIOClient", args: reason)
|
||||
|
||||
@@ -24,21 +24,9 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
@objc public enum SocketIOClientStatus: Int, CustomStringConvertible {
|
||||
case NotConnected, Closed, Connecting, Connected, Reconnecting
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case NotConnected:
|
||||
return "Not Connected"
|
||||
case Closed:
|
||||
return "Closed"
|
||||
case Connecting:
|
||||
return "Connecting"
|
||||
case Connected:
|
||||
return "Connected"
|
||||
case Reconnecting:
|
||||
return "Reconnecting"
|
||||
}
|
||||
}
|
||||
}
|
||||
/// **NotConnected**: initial state
|
||||
///
|
||||
/// **Disconnected**: connected before
|
||||
@objc public enum SocketIOClientStatus : Int {
|
||||
case NotConnected, Disconnected, Connecting, Connected
|
||||
}
|
||||
@@ -24,9 +24,9 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
public protocol SocketLogger: class {
|
||||
public protocol SocketLogger : class {
|
||||
/// Whether to log or not
|
||||
var log: Bool {get set}
|
||||
var log: Bool { get set }
|
||||
|
||||
/// Normal log messages
|
||||
func log(message: String, type: String, args: AnyObject...)
|
||||
@@ -54,7 +54,7 @@ public extension SocketLogger {
|
||||
}
|
||||
}
|
||||
|
||||
class DefaultSocketLogger: SocketLogger {
|
||||
class DefaultSocketLogger : SocketLogger {
|
||||
static var Logger: SocketLogger = DefaultSocketLogger()
|
||||
|
||||
var log = false
|
||||
|
||||
+48
-98
@@ -61,7 +61,7 @@ struct SocketPacket {
|
||||
return createPacketString()
|
||||
}
|
||||
|
||||
init(type: SocketPacket.PacketType, data: [AnyObject] = [AnyObject](), id: Int = -1,
|
||||
init(type: PacketType, data: [AnyObject] = [AnyObject](), id: Int = -1,
|
||||
nsp: String, placeholders: Int = 0, binary: [NSData] = [NSData]()) {
|
||||
self.data = data
|
||||
self.id = id
|
||||
@@ -86,108 +86,56 @@ struct SocketPacket {
|
||||
}
|
||||
}
|
||||
|
||||
private func completeMessage(message: String, ack: Bool) -> String {
|
||||
var restOfMessage = ""
|
||||
private func completeMessage(message: String) -> String {
|
||||
let restOfMessage: String
|
||||
|
||||
if data.count == 0 {
|
||||
return message + "]"
|
||||
return message + "[]"
|
||||
}
|
||||
|
||||
for arg in data {
|
||||
if arg is NSDictionary || arg is [AnyObject] {
|
||||
do {
|
||||
let jsonSend = try NSJSONSerialization.dataWithJSONObject(arg,
|
||||
options: NSJSONWritingOptions(rawValue: 0))
|
||||
let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding)
|
||||
|
||||
restOfMessage += jsonString! + ","
|
||||
} catch {
|
||||
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
|
||||
type: SocketPacket.logType)
|
||||
}
|
||||
} else if let str = arg as? String {
|
||||
restOfMessage += "\"" + ((str["\n"] <~ "\\\\n")["\r"] <~ "\\\\r") + "\","
|
||||
} else if arg is NSNull {
|
||||
restOfMessage += "null,"
|
||||
} else {
|
||||
restOfMessage += "\(arg),"
|
||||
do {
|
||||
let jsonSend = try NSJSONSerialization.dataWithJSONObject(data,
|
||||
options: NSJSONWritingOptions(rawValue: 0))
|
||||
guard let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding) else {
|
||||
return message + "[]"
|
||||
}
|
||||
|
||||
restOfMessage = jsonString
|
||||
} catch {
|
||||
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
|
||||
type: SocketPacket.logType)
|
||||
|
||||
restOfMessage = "[]"
|
||||
}
|
||||
|
||||
if restOfMessage != "" {
|
||||
restOfMessage.removeAtIndex(restOfMessage.endIndex.predecessor())
|
||||
}
|
||||
|
||||
return message + restOfMessage + "]"
|
||||
}
|
||||
|
||||
private func createAck() -> String {
|
||||
let message: String
|
||||
|
||||
if type == .Ack {
|
||||
if nsp == "/" {
|
||||
message = "3\(id)["
|
||||
} else {
|
||||
message = "3\(nsp),\(id)["
|
||||
}
|
||||
} else {
|
||||
if nsp == "/" {
|
||||
message = "6\(binary.count)-\(id)["
|
||||
} else {
|
||||
message = "6\(binary.count)-\(nsp),\(id)["
|
||||
}
|
||||
}
|
||||
|
||||
return completeMessage(message, ack: true)
|
||||
}
|
||||
|
||||
|
||||
private func createMessageForEvent() -> String {
|
||||
let message: String
|
||||
|
||||
if type == .Event {
|
||||
if nsp == "/" {
|
||||
if id == -1 {
|
||||
message = "2["
|
||||
} else {
|
||||
message = "2\(id)["
|
||||
}
|
||||
} else {
|
||||
if id == -1 {
|
||||
message = "2\(nsp),["
|
||||
} else {
|
||||
message = "2\(nsp),\(id)["
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if nsp == "/" {
|
||||
if id == -1 {
|
||||
message = "5\(binary.count)-["
|
||||
} else {
|
||||
message = "5\(binary.count)-\(id)["
|
||||
}
|
||||
} else {
|
||||
if id == -1 {
|
||||
message = "5\(binary.count)-\(nsp),["
|
||||
} else {
|
||||
message = "5\(binary.count)-\(nsp),\(id)["
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return completeMessage(message, ack: false)
|
||||
return message + restOfMessage
|
||||
}
|
||||
|
||||
private func createPacketString() -> String {
|
||||
let str: String
|
||||
let typeString = String(type.rawValue)
|
||||
let binaryCountString: String
|
||||
let nspString: String
|
||||
let idString: String
|
||||
|
||||
if type == .Event || type == .BinaryEvent {
|
||||
str = createMessageForEvent()
|
||||
if type == .BinaryEvent || type == .BinaryAck {
|
||||
binaryCountString = typeString + String(binary.count) + "-"
|
||||
} else {
|
||||
str = createAck()
|
||||
binaryCountString = typeString
|
||||
}
|
||||
|
||||
return str
|
||||
if nsp != "/" {
|
||||
nspString = binaryCountString + nsp + ","
|
||||
} else {
|
||||
nspString = binaryCountString
|
||||
}
|
||||
|
||||
if id != -1 {
|
||||
idString = nspString + String(id)
|
||||
} else {
|
||||
idString = nspString
|
||||
}
|
||||
|
||||
return completeMessage(idString)
|
||||
}
|
||||
|
||||
// Called when we have all the binary data for a packet
|
||||
@@ -197,19 +145,21 @@ struct SocketPacket {
|
||||
data = data.map(_fillInPlaceholders)
|
||||
}
|
||||
|
||||
// Helper method that looks for placeholder strings
|
||||
// Helper method that looks for placeholders
|
||||
// If object is a collection it will recurse
|
||||
// Returns the object if it is not a placeholder string or the corresponding
|
||||
// Returns the object if it is not a placeholder or the corresponding
|
||||
// binary data
|
||||
private func _fillInPlaceholders(object: AnyObject) -> AnyObject {
|
||||
switch object {
|
||||
case let string as String where string["~~(\\d)"].groups() != nil:
|
||||
return binary[Int(string["~~(\\d)"].groups()![1])!]
|
||||
case let dict as NSDictionary:
|
||||
return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in
|
||||
cur[keyValue.0 as! NSCopying] = _fillInPlaceholders(keyValue.1)
|
||||
return cur
|
||||
})
|
||||
if dict["_placeholder"] as? Bool ?? false {
|
||||
return binary[dict["num"] as! Int]
|
||||
} else {
|
||||
return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in
|
||||
cur[keyValue.0 as! NSCopying] = _fillInPlaceholders(keyValue.1)
|
||||
return cur
|
||||
})
|
||||
}
|
||||
case let arr as [AnyObject]:
|
||||
return arr.map(_fillInPlaceholders)
|
||||
default:
|
||||
@@ -237,7 +187,7 @@ extension SocketPacket {
|
||||
static func packetFromEmit(items: [AnyObject], id: Int, nsp: String, ack: Bool) -> SocketPacket {
|
||||
let (parsedData, binary) = deconstructData(items)
|
||||
let packet = SocketPacket(type: findType(binary.count, ack: ack), data: parsedData,
|
||||
id: id, nsp: nsp, placeholders: -1, binary: binary)
|
||||
id: id, nsp: nsp, binary: binary)
|
||||
|
||||
return packet
|
||||
}
|
||||
|
||||
+26
-32
@@ -22,7 +22,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol SocketParsable: SocketClientSpec {
|
||||
protocol SocketParsable : SocketIOClientSpec {
|
||||
func parseBinaryData(data: NSData)
|
||||
func parseSocketMessage(message: String)
|
||||
}
|
||||
@@ -35,8 +35,6 @@ extension SocketParsable {
|
||||
private func handleConnect(p: SocketPacket) {
|
||||
if p.nsp == "/" && nsp != "/" {
|
||||
joinNamespace(nsp)
|
||||
} else if p.nsp != "/" && nsp == "/" {
|
||||
didConnect()
|
||||
} else {
|
||||
didConnect()
|
||||
}
|
||||
@@ -45,20 +43,19 @@ extension SocketParsable {
|
||||
private func handlePacket(pack: SocketPacket) {
|
||||
switch pack.type {
|
||||
case .Event where isCorrectNamespace(pack.nsp):
|
||||
handleEvent(pack.event, data: pack.args,
|
||||
isInternalMessage: false, withAck: pack.id)
|
||||
handleEvent(pack.event, data: pack.args, isInternalMessage: false, withAck: pack.id)
|
||||
case .Ack where isCorrectNamespace(pack.nsp):
|
||||
handleAck(pack.id, data: pack.data)
|
||||
case .BinaryEvent where isCorrectNamespace(pack.nsp):
|
||||
waitingData.append(pack)
|
||||
waitingPackets.append(pack)
|
||||
case .BinaryAck where isCorrectNamespace(pack.nsp):
|
||||
waitingData.append(pack)
|
||||
waitingPackets.append(pack)
|
||||
case .Connect:
|
||||
handleConnect(pack)
|
||||
case .Disconnect:
|
||||
didDisconnect("Got Disconnect")
|
||||
case .Error:
|
||||
handleEvent("error", data: pack.data, isInternalMessage: false, withAck: pack.id)
|
||||
handleEvent("error", data: pack.data, isInternalMessage: true, withAck: pack.id)
|
||||
default:
|
||||
DefaultSocketLogger.Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description)
|
||||
}
|
||||
@@ -76,7 +73,7 @@ extension SocketParsable {
|
||||
return .Right(SocketPacket(type: type, nsp: "/"))
|
||||
}
|
||||
|
||||
var namespace: String?
|
||||
var namespace = "/"
|
||||
var placeholders = -1
|
||||
|
||||
if type == .BinaryEvent || type == .BinaryAck {
|
||||
@@ -92,50 +89,49 @@ extension SocketParsable {
|
||||
}
|
||||
|
||||
if !parser.hasNext {
|
||||
return .Right(SocketPacket(type: type, id: -1,
|
||||
nsp: namespace ?? "/", placeholders: placeholders))
|
||||
return .Right(SocketPacket(type: type, nsp: namespace, placeholders: placeholders))
|
||||
}
|
||||
|
||||
var idString = ""
|
||||
|
||||
if type == .Error {
|
||||
parser.advanceIndexBy(-1)
|
||||
}
|
||||
|
||||
while parser.hasNext && type != .Error {
|
||||
if let int = Int(parser.read(1)) {
|
||||
idString += String(int)
|
||||
} else {
|
||||
parser.advanceIndexBy(-2)
|
||||
break
|
||||
} else {
|
||||
while parser.hasNext {
|
||||
if let int = Int(parser.read(1)) {
|
||||
idString += String(int)
|
||||
} else {
|
||||
parser.advanceIndexBy(-2)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let d = message[parser.currentIndex.advancedBy(1)..<message.endIndex]
|
||||
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] <~ "\"~~$2\""
|
||||
|
||||
switch parseData(noPlaceholders) {
|
||||
switch parseData(d) {
|
||||
case let .Left(err):
|
||||
// If first you don't succeed, try again
|
||||
if case let .Right(data) = parseData("\([noPlaceholders as AnyObject])") {
|
||||
// Errors aren't always enclosed in an array
|
||||
if case let .Right(data) = parseData("\([d as AnyObject])") {
|
||||
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
|
||||
nsp: namespace ?? "/", placeholders: placeholders))
|
||||
nsp: namespace, placeholders: placeholders))
|
||||
} else {
|
||||
return .Left(err)
|
||||
}
|
||||
case let .Right(data):
|
||||
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
|
||||
nsp: namespace ?? "/", placeholders: placeholders))
|
||||
nsp: namespace, placeholders: placeholders))
|
||||
}
|
||||
}
|
||||
|
||||
// Parses data for events
|
||||
private func parseData(data: String) -> Either<String, [AnyObject]> {
|
||||
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
||||
|
||||
do {
|
||||
if let arr = try NSJSONSerialization.JSONObjectWithData(stringData!,
|
||||
options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] {
|
||||
return .Right(arr)
|
||||
options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] {
|
||||
return .Right(arr)
|
||||
} else {
|
||||
return .Left("Expected data array")
|
||||
}
|
||||
@@ -160,17 +156,15 @@ extension SocketParsable {
|
||||
}
|
||||
|
||||
func parseBinaryData(data: NSData) {
|
||||
guard !waitingData.isEmpty else {
|
||||
guard !waitingPackets.isEmpty else {
|
||||
DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser")
|
||||
return
|
||||
}
|
||||
|
||||
// Should execute event?
|
||||
guard waitingData[waitingData.count - 1].addData(data) else {
|
||||
return
|
||||
}
|
||||
guard waitingPackets[waitingPackets.count - 1].addData(data) else { return }
|
||||
|
||||
let packet = waitingData.removeLast()
|
||||
let packet = waitingPackets.removeLast()
|
||||
|
||||
if packet.type != .BinaryAck {
|
||||
handleEvent(packet.event, data: packet.args ?? [],
|
||||
|
||||
@@ -65,4 +65,4 @@ struct SocketStringReader {
|
||||
mutating func readUntilEnd() -> String {
|
||||
return read(currentIndex.distanceTo(message.endIndex))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,9 @@ public typealias AckCallback = ([AnyObject]) -> Void
|
||||
public typealias NormalCallback = ([AnyObject], SocketAckEmitter) -> Void
|
||||
public typealias OnAckCallback = (timeoutAfter: UInt64, callback: AckCallback) -> Void
|
||||
|
||||
typealias Probe = (msg: String, type: SocketEnginePacketType, data: [NSData])
|
||||
typealias ProbeWaitQueue = [Probe]
|
||||
|
||||
enum Either<E, V> {
|
||||
case Left(E)
|
||||
case Right(V)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
//
|
||||
// String.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Yannick Loriot on 5/4/16.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
extension String {
|
||||
func urlEncode() -> String? {
|
||||
return stringByAddingPercentEncodingWithAllowedCharacters(.allowedURLCharacterSet)
|
||||
}
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
//
|
||||
// SwiftRegex.swift
|
||||
// SwiftRegex
|
||||
//
|
||||
// Created by John Holdsworth on 26/06/2014.
|
||||
// Copyright (c) 2014 John Holdsworth.
|
||||
//
|
||||
// $Id: //depot/SwiftRegex/SwiftRegex.swift#37 $
|
||||
//
|
||||
// This code is in the public domain from:
|
||||
// https://github.com/johnno1962/SwiftRegex
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
infix operator <~ { associativity none precedence 130 }
|
||||
|
||||
private var swiftRegexCache = [String: NSRegularExpression]()
|
||||
|
||||
internal final class SwiftRegex: NSObject, BooleanType {
|
||||
var target:String
|
||||
var regex: NSRegularExpression
|
||||
|
||||
init(target:String, pattern:String, options:NSRegularExpressionOptions?) {
|
||||
self.target = target
|
||||
if let regex = swiftRegexCache[pattern] {
|
||||
self.regex = regex
|
||||
} else {
|
||||
do {
|
||||
let regex = try NSRegularExpression(pattern: pattern, options:
|
||||
NSRegularExpressionOptions.DotMatchesLineSeparators)
|
||||
swiftRegexCache[pattern] = regex
|
||||
self.regex = regex
|
||||
} catch let error as NSError {
|
||||
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
|
||||
self.regex = NSRegularExpression()
|
||||
}
|
||||
}
|
||||
super.init()
|
||||
}
|
||||
|
||||
private static func failure(message: String) {
|
||||
fatalError("SwiftRegex: \(message)")
|
||||
}
|
||||
|
||||
private var targetRange: NSRange {
|
||||
return NSRange(location: 0,length: target.utf16.count)
|
||||
}
|
||||
|
||||
private func substring(range: NSRange) -> String? {
|
||||
if range.location != NSNotFound {
|
||||
return (target as NSString).substringWithRange(range)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func doesMatch(options: NSMatchingOptions!) -> Bool {
|
||||
return range(options).location != NSNotFound
|
||||
}
|
||||
|
||||
func range(options: NSMatchingOptions) -> NSRange {
|
||||
return regex.rangeOfFirstMatchInString(target as String, options: [], range: targetRange)
|
||||
}
|
||||
|
||||
func match(options: NSMatchingOptions) -> String? {
|
||||
return substring(range(options))
|
||||
}
|
||||
|
||||
func groups() -> [String]? {
|
||||
return groupsForMatch(regex.firstMatchInString(target as String, options:
|
||||
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange))
|
||||
}
|
||||
|
||||
private func groupsForMatch(match: NSTextCheckingResult?) -> [String]? {
|
||||
guard let match = match else {
|
||||
return nil
|
||||
}
|
||||
var groups = [String]()
|
||||
for groupno in 0...regex.numberOfCaptureGroups {
|
||||
if let group = substring(match.rangeAtIndex(groupno)) {
|
||||
groups += [group]
|
||||
} else {
|
||||
groups += ["_"] // avoids bridging problems
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
subscript(groupno: Int) -> String? {
|
||||
get {
|
||||
return groups()?[groupno]
|
||||
}
|
||||
|
||||
set(newValue) {
|
||||
if newValue == nil {
|
||||
return
|
||||
}
|
||||
|
||||
for match in Array(matchResults().reverse()) {
|
||||
let replacement = regex.replacementStringForResult(match,
|
||||
inString: target as String, offset: 0, template: newValue!)
|
||||
let mut = NSMutableString(string: target)
|
||||
mut.replaceCharactersInRange(match.rangeAtIndex(groupno), withString: replacement)
|
||||
|
||||
target = mut as String
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func matchResults() -> [NSTextCheckingResult] {
|
||||
let matches = regex.matchesInString(target as String, options:
|
||||
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange)
|
||||
as [NSTextCheckingResult]
|
||||
|
||||
return matches
|
||||
}
|
||||
|
||||
func ranges() -> [NSRange] {
|
||||
return matchResults().map { $0.range }
|
||||
}
|
||||
|
||||
func matches() -> [String] {
|
||||
return matchResults().map( { self.substring($0.range)!})
|
||||
}
|
||||
|
||||
func allGroups() -> [[String]?] {
|
||||
return matchResults().map { self.groupsForMatch($0) }
|
||||
}
|
||||
|
||||
func dictionary(options: NSMatchingOptions!) -> Dictionary<String,String> {
|
||||
var out = Dictionary<String,String>()
|
||||
for match in matchResults() {
|
||||
out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))!
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String),
|
||||
options:NSMatchingOptions) -> String {
|
||||
let out = NSMutableString()
|
||||
var pos = 0
|
||||
|
||||
regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {match, flags, stop in
|
||||
let matchRange = match!.range
|
||||
out.appendString( self.substring(NSRange(location:pos, length:matchRange.location-pos))!)
|
||||
out.appendString( substitution(match!, stop) )
|
||||
pos = matchRange.location + matchRange.length
|
||||
}
|
||||
|
||||
out.appendString(substring(NSRange(location:pos, length:targetRange.length-pos))!)
|
||||
|
||||
return out as String
|
||||
}
|
||||
|
||||
var boolValue: Bool {
|
||||
return doesMatch(nil)
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex {
|
||||
return SwiftRegex(target: self, pattern: pattern, options: options)
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
subscript(pattern: String) -> SwiftRegex {
|
||||
return SwiftRegex(target: self, pattern: pattern, options: nil)
|
||||
}
|
||||
}
|
||||
|
||||
func <~ (left: SwiftRegex, right: String) -> String {
|
||||
return left.substituteMatches({match, stop in
|
||||
return left.regex.replacementStringForResult( match,
|
||||
inString: left.target as String, offset: 0, template: right )
|
||||
}, options: [])
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// SSLSecurity.swift
|
||||
// Starscream
|
||||
//
|
||||
// Created by Dalton Cherry on 5/16/15.
|
||||
// Copyright (c) 2014-2015 Dalton Cherry.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
import Foundation
|
||||
import Security
|
||||
|
||||
public class SSLCert : NSObject {
|
||||
var certData: NSData?
|
||||
var key: SecKeyRef?
|
||||
|
||||
/**
|
||||
Designated init for certificates
|
||||
|
||||
- parameter data: is the binary data of the certificate
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
public init(data: NSData) {
|
||||
self.certData = data
|
||||
}
|
||||
|
||||
/**
|
||||
Designated init for public keys
|
||||
|
||||
- parameter key: is the public key to be used
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
public init(key: SecKeyRef) {
|
||||
self.key = key
|
||||
}
|
||||
}
|
||||
|
||||
public class SSLSecurity : NSObject {
|
||||
public var validatedDN = true //should the domain name be validated?
|
||||
|
||||
var isReady = false //is the key processing done?
|
||||
var certificates: [NSData]? //the certificates
|
||||
var pubKeys: [SecKeyRef]? //the public keys
|
||||
var usePublicKeys = false //use public keys or certificate validation?
|
||||
|
||||
/**
|
||||
Use certs from main app bundle
|
||||
|
||||
- parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
public convenience init(usePublicKeys: Bool = false) {
|
||||
let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".")
|
||||
|
||||
let certs = paths.reduce([SSLCert]()) { (certs: [SSLCert], path: String) -> [SSLCert] in
|
||||
var certs = certs
|
||||
if let data = NSData(contentsOfFile: path) {
|
||||
certs.append(SSLCert(data: data))
|
||||
}
|
||||
return certs
|
||||
}
|
||||
|
||||
self.init(certs: certs, usePublicKeys: usePublicKeys)
|
||||
}
|
||||
|
||||
/**
|
||||
Designated init
|
||||
|
||||
- parameter keys: is the certificates or public keys to use
|
||||
- parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
public init(certs: [SSLCert], usePublicKeys: Bool) {
|
||||
super.init()
|
||||
|
||||
self.usePublicKeys = usePublicKeys
|
||||
|
||||
if self.usePublicKeys {
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) {
|
||||
let pubKeys = certs.reduce([SecKeyRef]()) { (pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in
|
||||
var pubKeys = pubKeys
|
||||
if let data = cert.certData where cert.key == nil {
|
||||
cert.key = self.extractPublicKey(data)
|
||||
}
|
||||
if let key = cert.key {
|
||||
pubKeys.append(key)
|
||||
}
|
||||
return pubKeys
|
||||
}
|
||||
|
||||
self.pubKeys = pubKeys
|
||||
self.isReady = true
|
||||
}
|
||||
} else {
|
||||
let certificates = certs.reduce([NSData]()) { (certificates: [NSData], cert: SSLCert) -> [NSData] in
|
||||
var certificates = certificates
|
||||
if let data = cert.certData {
|
||||
certificates.append(data)
|
||||
}
|
||||
return certificates
|
||||
}
|
||||
self.certificates = certificates
|
||||
self.isReady = true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Valid the trust and domain name.
|
||||
|
||||
- parameter trust: is the serverTrust to validate
|
||||
- parameter domain: is the CN domain to validate
|
||||
|
||||
- returns: if the key was successfully validated
|
||||
*/
|
||||
public func isValid(trust: SecTrustRef, domain: String?) -> Bool {
|
||||
|
||||
var tries = 0
|
||||
while(!self.isReady) {
|
||||
usleep(1000)
|
||||
tries += 1
|
||||
if tries > 5 {
|
||||
return false //doesn't appear it is going to ever be ready...
|
||||
}
|
||||
}
|
||||
var policy: SecPolicyRef
|
||||
if self.validatedDN {
|
||||
policy = SecPolicyCreateSSL(true, domain)
|
||||
} else {
|
||||
policy = SecPolicyCreateBasicX509()
|
||||
}
|
||||
SecTrustSetPolicies(trust,policy)
|
||||
if self.usePublicKeys {
|
||||
if let keys = self.pubKeys {
|
||||
let serverPubKeys = publicKeyChainForTrust(trust)
|
||||
for serverKey in serverPubKeys as [AnyObject] {
|
||||
for key in keys as [AnyObject] {
|
||||
if serverKey.isEqual(key) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if let certs = self.certificates {
|
||||
let serverCerts = certificateChainForTrust(trust)
|
||||
var collect = [SecCertificate]()
|
||||
for cert in certs {
|
||||
collect.append(SecCertificateCreateWithData(nil,cert)!)
|
||||
}
|
||||
SecTrustSetAnchorCertificates(trust,collect)
|
||||
var result: SecTrustResultType = 0
|
||||
SecTrustEvaluate(trust,&result)
|
||||
let r = Int(result)
|
||||
if r == kSecTrustResultUnspecified || r == kSecTrustResultProceed {
|
||||
var trustedCount = 0
|
||||
for serverCert in serverCerts {
|
||||
for cert in certs {
|
||||
if cert == serverCert {
|
||||
trustedCount += 1
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if trustedCount == serverCerts.count {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
Get the public key from a certificate data
|
||||
|
||||
- parameter data: is the certificate to pull the public key from
|
||||
|
||||
- returns: a public key
|
||||
*/
|
||||
func extractPublicKey(data: NSData) -> SecKeyRef? {
|
||||
guard let cert = SecCertificateCreateWithData(nil, data) else { return nil }
|
||||
|
||||
return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509())
|
||||
}
|
||||
|
||||
/**
|
||||
Get the public key from a certificate
|
||||
|
||||
- parameter data: is the certificate to pull the public key from
|
||||
|
||||
- returns: a public key
|
||||
*/
|
||||
func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? {
|
||||
var possibleTrust: SecTrust?
|
||||
SecTrustCreateWithCertificates(cert, policy, &possibleTrust)
|
||||
|
||||
guard let trust = possibleTrust else { return nil }
|
||||
|
||||
var result: SecTrustResultType = 0
|
||||
SecTrustEvaluate(trust, &result)
|
||||
return SecTrustCopyPublicKey(trust)
|
||||
}
|
||||
|
||||
/**
|
||||
Get the certificate chain for the trust
|
||||
|
||||
- parameter trust: is the trust to lookup the certificate chain for
|
||||
|
||||
- returns: the certificate chain for the trust
|
||||
*/
|
||||
func certificateChainForTrust(trust: SecTrustRef) -> [NSData] {
|
||||
let certificates = (0..<SecTrustGetCertificateCount(trust)).reduce([NSData]()) { (certificates: [NSData], index: Int) -> [NSData] in
|
||||
var certificates = certificates
|
||||
let cert = SecTrustGetCertificateAtIndex(trust, index)
|
||||
certificates.append(SecCertificateCopyData(cert!))
|
||||
return certificates
|
||||
}
|
||||
|
||||
return certificates
|
||||
}
|
||||
|
||||
/**
|
||||
Get the public key chain for the trust
|
||||
|
||||
- parameter trust: is the trust to lookup the certificate chain and extract the public keys
|
||||
|
||||
- returns: the public keys from the certifcate chain for the trust
|
||||
*/
|
||||
func publicKeyChainForTrust(trust: SecTrustRef) -> [SecKeyRef] {
|
||||
let policy = SecPolicyCreateBasicX509()
|
||||
let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKeyRef]()) { (keys: [SecKeyRef], index: Int) -> [SecKeyRef] in
|
||||
var keys = keys
|
||||
let cert = SecTrustGetCertificateAtIndex(trust, index)
|
||||
if let key = extractPublicKeyFromCert(cert!, policy: policy) {
|
||||
keys.append(key)
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -23,6 +23,10 @@ import Foundation
|
||||
import CoreFoundation
|
||||
import Security
|
||||
|
||||
public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification"
|
||||
public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification"
|
||||
public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName"
|
||||
|
||||
public protocol WebSocketDelegate: class {
|
||||
func websocketDidConnect(socket: WebSocket)
|
||||
func websocketDidDisconnect(socket: WebSocket, error: NSError?)
|
||||
@@ -109,15 +113,17 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
public var headers = [String: String]()
|
||||
public var voipEnabled = false
|
||||
public var selfSignedSSL = false
|
||||
private var security: SSLSecurity?
|
||||
public var security: SSLSecurity?
|
||||
public var enabledSSLCipherSuites: [SSLCipherSuite]?
|
||||
public var origin: String?
|
||||
public var timeout = 5
|
||||
public var isConnected :Bool {
|
||||
return connected
|
||||
}
|
||||
public var currentURL: NSURL {return url}
|
||||
private var url: NSURL
|
||||
private var inputStream: NSInputStream?
|
||||
private var outputStream: NSOutputStream?
|
||||
private var isRunLoop = false
|
||||
private var connected = false
|
||||
private var isCreated = false
|
||||
private var writeQueue = NSOperationQueue()
|
||||
@@ -126,10 +132,22 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
private var fragBuffer: NSData?
|
||||
private var certValidated = false
|
||||
private var didDisconnect = false
|
||||
private var readyToWrite = false
|
||||
private let mutex = NSLock()
|
||||
private let notificationCenter = NSNotificationCenter.defaultCenter()
|
||||
private var canDispatch: Bool {
|
||||
mutex.lock()
|
||||
let canWork = readyToWrite
|
||||
mutex.unlock()
|
||||
return canWork
|
||||
}
|
||||
//the shared processing queue used for all websocket
|
||||
private static let sharedWorkQueue = dispatch_queue_create("com.vluxe.starscream.websocket", DISPATCH_QUEUE_SERIAL)
|
||||
|
||||
//used for setting protocols.
|
||||
public init(url: NSURL, protocols: [String]? = nil) {
|
||||
self.url = url
|
||||
self.origin = url.absoluteString
|
||||
writeQueue.maxConcurrentOperationCount = 1
|
||||
optionalProtocols = protocols
|
||||
}
|
||||
@@ -137,15 +155,10 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
///Connect to the websocket server on a background thread
|
||||
public func connect() {
|
||||
guard !isCreated else { return }
|
||||
|
||||
dispatch_async(queue) { [weak self] in
|
||||
self?.didDisconnect = false
|
||||
}
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) { [weak self] in
|
||||
self?.isCreated = true
|
||||
self?.createHTTPRequest()
|
||||
self?.isCreated = false
|
||||
}
|
||||
didDisconnect = false
|
||||
isCreated = true
|
||||
createHTTPRequest()
|
||||
isCreated = false
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -160,8 +173,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
public func disconnect(forceTimeout forceTimeout: NSTimeInterval? = nil) {
|
||||
switch forceTimeout {
|
||||
case .Some(let seconds) where seconds > 0:
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), queue) { [unowned self] in
|
||||
self.disconnectStream(nil)
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), queue) { [weak self] in
|
||||
self?.disconnectStream(nil)
|
||||
}
|
||||
fallthrough
|
||||
case .None:
|
||||
@@ -173,28 +186,44 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
///write a string to the websocket. This sends it as a text frame.
|
||||
public func writeString(str: String) {
|
||||
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame)
|
||||
/**
|
||||
Write a string to the websocket. This sends it as a text frame.
|
||||
|
||||
If you supply a non-nil completion block, I will perform it when the write completes.
|
||||
|
||||
- parameter str: The string to write.
|
||||
- parameter completion: The (optional) completion handler.
|
||||
*/
|
||||
public func writeString(str: String, completion: (() -> ())? = nil) {
|
||||
guard isConnected else { return }
|
||||
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame, writeCompletion: completion)
|
||||
}
|
||||
|
||||
///write binary data to the websocket. This sends it as a binary frame.
|
||||
public func writeData(data: NSData) {
|
||||
dequeueWrite(data, code: .BinaryFrame)
|
||||
/**
|
||||
Write binary data to the websocket. This sends it as a binary frame.
|
||||
|
||||
If you supply a non-nil completion block, I will perform it when the write completes.
|
||||
|
||||
- parameter data: The data to write.
|
||||
- parameter completion: The (optional) completion handler.
|
||||
*/
|
||||
public func writeData(data: NSData, completion: (() -> ())? = nil) {
|
||||
guard isConnected else { return }
|
||||
dequeueWrite(data, code: .BinaryFrame, writeCompletion: completion)
|
||||
}
|
||||
|
||||
//write a ping to the websocket. This sends it as a control frame.
|
||||
//yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
|
||||
public func writePing(data: NSData) {
|
||||
dequeueWrite(data, code: .Ping)
|
||||
public func writePing(data: NSData, completion: (() -> ())? = nil) {
|
||||
guard isConnected else { return }
|
||||
dequeueWrite(data, code: .Ping, writeCompletion: completion)
|
||||
}
|
||||
//private methods below!
|
||||
|
||||
//private method that starts the connection
|
||||
private func createHTTPRequest() {
|
||||
|
||||
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
|
||||
url, kCFHTTPVersion1_1).takeRetainedValue()
|
||||
url, kCFHTTPVersion1_1).takeRetainedValue()
|
||||
|
||||
var port = url.port
|
||||
if port == nil {
|
||||
@@ -211,7 +240,9 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
|
||||
addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey())
|
||||
addHeader(urlRequest, key: headerOriginName, val: url.absoluteString)
|
||||
if let origin = origin {
|
||||
addHeader(urlRequest, key: headerOriginName, val: origin)
|
||||
}
|
||||
addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
|
||||
for (key,value) in headers {
|
||||
addHeader(urlRequest, key: key, val: value)
|
||||
@@ -221,10 +252,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
initStreamsWithData(serializedRequest, Int(port!))
|
||||
}
|
||||
}
|
||||
|
||||
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
|
||||
private func addHeader(urlRequest: CFHTTPMessage, key: NSString, val: NSString) {
|
||||
CFHTTPMessageSetHeaderFieldValue(urlRequest, key, val)
|
||||
}
|
||||
|
||||
//generate a websocket key as needed in rfc
|
||||
private func generateWebSocketKey() -> String {
|
||||
var key = ""
|
||||
@@ -237,6 +270,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
|
||||
return baseKey!
|
||||
}
|
||||
|
||||
//Start the stream connection and write the data to the output stream
|
||||
private func initStreamsWithData(data: NSData, _ port: Int) {
|
||||
//higher level API we will cut over to at some point
|
||||
@@ -269,29 +303,44 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if let cipherSuites = self.enabledSSLCipherSuites {
|
||||
if let sslContextIn = CFReadStreamCopyProperty(inputStream, kCFStreamPropertySSLContext) as! SSLContextRef?,
|
||||
sslContextOut = CFWriteStreamCopyProperty(outputStream, kCFStreamPropertySSLContext) as! SSLContextRef? {
|
||||
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
|
||||
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
|
||||
if resIn != errSecSuccess {
|
||||
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
|
||||
disconnectStream(error)
|
||||
return
|
||||
}
|
||||
if resOut != errSecSuccess {
|
||||
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
|
||||
disconnectStream(error)
|
||||
return
|
||||
}
|
||||
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
|
||||
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
|
||||
if resIn != errSecSuccess {
|
||||
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
|
||||
disconnectStream(error)
|
||||
return
|
||||
}
|
||||
if resOut != errSecSuccess {
|
||||
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
|
||||
disconnectStream(error)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
isRunLoop = true
|
||||
inStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
outStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue)
|
||||
CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue)
|
||||
inStream.open()
|
||||
outStream.open()
|
||||
|
||||
self.mutex.lock()
|
||||
self.readyToWrite = true
|
||||
self.mutex.unlock()
|
||||
|
||||
let bytes = UnsafePointer<UInt8>(data.bytes)
|
||||
outStream.write(bytes, maxLength: data.length)
|
||||
while(isRunLoop) {
|
||||
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as NSDate)
|
||||
var out = timeout * 1000000 //wait 5 seconds before giving up
|
||||
writeQueue.addOperationWithBlock { [weak self] in
|
||||
while !outStream.hasSpaceAvailable {
|
||||
usleep(100) //wait until the socket is ready
|
||||
out -= 100
|
||||
if out < 0 {
|
||||
self?.cleanupStream()
|
||||
self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2))
|
||||
return
|
||||
} else if outStream.streamError != nil {
|
||||
return //disconnectStream will be called.
|
||||
}
|
||||
}
|
||||
outStream.write(bytes, maxLength: data.length)
|
||||
}
|
||||
}
|
||||
//delegate for the stream methods. Processes incoming bytes
|
||||
@@ -322,20 +371,28 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
//disconnect the stream object
|
||||
private func disconnectStream(error: NSError?) {
|
||||
writeQueue.waitUntilAllOperationsAreFinished()
|
||||
if error == nil {
|
||||
writeQueue.waitUntilAllOperationsAreFinished()
|
||||
} else {
|
||||
writeQueue.cancelAllOperations()
|
||||
}
|
||||
cleanupStream()
|
||||
doDisconnect(error)
|
||||
}
|
||||
|
||||
private func cleanupStream() {
|
||||
outputStream?.delegate = nil
|
||||
inputStream?.delegate = nil
|
||||
if let stream = inputStream {
|
||||
stream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
CFReadStreamSetDispatchQueue(stream, nil)
|
||||
stream.close()
|
||||
}
|
||||
if let stream = outputStream {
|
||||
stream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
CFWriteStreamSetDispatchQueue(stream, nil)
|
||||
stream.close()
|
||||
}
|
||||
outputStream = nil
|
||||
isRunLoop = false
|
||||
certValidated = false
|
||||
doDisconnect(error)
|
||||
connected = false
|
||||
inputStream = nil
|
||||
}
|
||||
|
||||
///handles the incoming bytes and sending them to the proper processing method
|
||||
@@ -345,52 +402,65 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
|
||||
|
||||
guard length > 0 else { return }
|
||||
|
||||
if !connected {
|
||||
connected = processHTTP(buffer, bufferLen: length)
|
||||
if !connected {
|
||||
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
|
||||
CFHTTPMessageAppendBytes(response, buffer, length)
|
||||
let code = CFHTTPMessageGetResponseStatusCode(response)
|
||||
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
|
||||
}
|
||||
} else {
|
||||
var process = false
|
||||
if inputQueue.count == 0 {
|
||||
process = true
|
||||
}
|
||||
inputQueue.append(NSData(bytes: buffer, length: length))
|
||||
if process {
|
||||
dequeueInput()
|
||||
}
|
||||
var process = false
|
||||
if inputQueue.count == 0 {
|
||||
process = true
|
||||
}
|
||||
inputQueue.append(NSData(bytes: buffer, length: length))
|
||||
if process {
|
||||
dequeueInput()
|
||||
}
|
||||
}
|
||||
///dequeue the incoming input so it is processed in order
|
||||
private func dequeueInput() {
|
||||
guard !inputQueue.isEmpty else { return }
|
||||
|
||||
let data = inputQueue[0]
|
||||
var work = data
|
||||
if let fragBuffer = fragBuffer {
|
||||
let combine = NSMutableData(data: fragBuffer)
|
||||
combine.appendData(data)
|
||||
work = combine
|
||||
self.fragBuffer = nil
|
||||
while !inputQueue.isEmpty {
|
||||
let data = inputQueue[0]
|
||||
var work = data
|
||||
if let fragBuffer = fragBuffer {
|
||||
let combine = NSMutableData(data: fragBuffer)
|
||||
combine.appendData(data)
|
||||
work = combine
|
||||
self.fragBuffer = nil
|
||||
}
|
||||
let buffer = UnsafePointer<UInt8>(work.bytes)
|
||||
let length = work.length
|
||||
if !connected {
|
||||
processTCPHandshake(buffer, bufferLen: length)
|
||||
} else {
|
||||
processRawMessagesInBuffer(buffer, bufferLen: length)
|
||||
}
|
||||
inputQueue = inputQueue.filter{$0 != data}
|
||||
}
|
||||
let buffer = UnsafePointer<UInt8>(work.bytes)
|
||||
processRawMessage(buffer, bufferLen: work.length)
|
||||
inputQueue = inputQueue.filter{$0 != data}
|
||||
dequeueInput()
|
||||
}
|
||||
|
||||
//handle checking the inital connection status
|
||||
private func processTCPHandshake(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
||||
let code = processHTTP(buffer, bufferLen: bufferLen)
|
||||
switch code {
|
||||
case 0:
|
||||
connected = true
|
||||
guard canDispatch else {return}
|
||||
dispatch_async(queue) { [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.onConnect?()
|
||||
s.delegate?.websocketDidConnect(s)
|
||||
s.notificationCenter.postNotificationName(WebsocketDidConnectNotification, object: self)
|
||||
}
|
||||
case -1:
|
||||
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
||||
break //do nothing, we are going to collect more data
|
||||
default:
|
||||
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
|
||||
}
|
||||
}
|
||||
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
|
||||
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
|
||||
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
|
||||
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
|
||||
var k = 0
|
||||
var totalSize = 0
|
||||
for i in 0..<bufferLen {
|
||||
if buffer[i] == CRLFBytes[k] {
|
||||
k++
|
||||
k += 1
|
||||
if k == 3 {
|
||||
totalSize = i + 1
|
||||
break
|
||||
@@ -400,39 +470,37 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
}
|
||||
if totalSize > 0 {
|
||||
if validateResponse(buffer, bufferLen: totalSize) {
|
||||
dispatch_async(queue) { [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.onConnect?()
|
||||
s.delegate?.websocketDidConnect(s)
|
||||
}
|
||||
totalSize += 1 //skip the last \n
|
||||
let restSize = bufferLen - totalSize
|
||||
if restSize > 0 {
|
||||
processRawMessage((buffer+totalSize),bufferLen: restSize)
|
||||
}
|
||||
return true
|
||||
let code = validateResponse(buffer, bufferLen: totalSize)
|
||||
if code != 0 {
|
||||
return code
|
||||
}
|
||||
totalSize += 1 //skip the last \n
|
||||
let restSize = bufferLen - totalSize
|
||||
if restSize > 0 {
|
||||
processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize)
|
||||
}
|
||||
return 0 //success
|
||||
}
|
||||
return false
|
||||
return -1 //was unable to find the full TCP header
|
||||
}
|
||||
|
||||
///validates the HTTP is a 101 as per the RFC spec
|
||||
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
|
||||
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
|
||||
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
|
||||
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
|
||||
if CFHTTPMessageGetResponseStatusCode(response) != 101 {
|
||||
return false
|
||||
let code = CFHTTPMessageGetResponseStatusCode(response)
|
||||
if code != 101 {
|
||||
return code
|
||||
}
|
||||
if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {
|
||||
let headers = cfHeaders.takeRetainedValue() as NSDictionary
|
||||
if let acceptKey = headers[headerWSAcceptName] as? NSString {
|
||||
if acceptKey.length > 0 {
|
||||
return true
|
||||
return 0
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
return -1
|
||||
}
|
||||
|
||||
///read a 16 bit big endian value from a buffer
|
||||
@@ -462,12 +530,15 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
///process the websocket data
|
||||
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
||||
/// Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process.
|
||||
@warn_unused_result
|
||||
private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> {
|
||||
let response = readStack.last
|
||||
let baseAddress = buffer.baseAddress
|
||||
let bufferLen = buffer.count
|
||||
if response != nil && bufferLen < 2 {
|
||||
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
||||
return
|
||||
fragBuffer = NSData(buffer: buffer)
|
||||
return emptyBuffer
|
||||
}
|
||||
if let response = response where response.bytesLeft > 0 {
|
||||
var len = response.bytesLeft
|
||||
@@ -477,45 +548,41 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
extra = 0
|
||||
}
|
||||
response.bytesLeft -= len
|
||||
response.buffer?.appendData(NSData(bytes: buffer, length: len))
|
||||
response.buffer?.appendData(NSData(bytes: baseAddress, length: len))
|
||||
processResponse(response)
|
||||
let offset = bufferLen - extra
|
||||
if extra > 0 {
|
||||
processExtra((buffer+offset), bufferLen: extra)
|
||||
}
|
||||
return
|
||||
return buffer.fromOffset(bufferLen - extra)
|
||||
} else {
|
||||
let isFin = (FinMask & buffer[0])
|
||||
let receivedOpcode = OpCode(rawValue: (OpCodeMask & buffer[0]))
|
||||
let isMasked = (MaskMask & buffer[1])
|
||||
let payloadLen = (PayloadLenMask & buffer[1])
|
||||
let isFin = (FinMask & baseAddress[0])
|
||||
let receivedOpcode = OpCode(rawValue: (OpCodeMask & baseAddress[0]))
|
||||
let isMasked = (MaskMask & baseAddress[1])
|
||||
let payloadLen = (PayloadLenMask & baseAddress[1])
|
||||
var offset = 2
|
||||
if (isMasked > 0 || (RSVMask & buffer[0]) > 0) && receivedOpcode != .Pong {
|
||||
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .Pong {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
return emptyBuffer
|
||||
}
|
||||
let isControlFrame = (receivedOpcode == .ConnectionClose || receivedOpcode == .Ping)
|
||||
if !isControlFrame && (receivedOpcode != .BinaryFrame && receivedOpcode != .ContinueFrame &&
|
||||
receivedOpcode != .TextFrame && receivedOpcode != .Pong) {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
|
||||
writeError(errCode)
|
||||
return emptyBuffer
|
||||
}
|
||||
if isControlFrame && isFin == 0 {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
return emptyBuffer
|
||||
}
|
||||
if receivedOpcode == .ConnectionClose {
|
||||
var code = CloseCode.Normal.rawValue
|
||||
if payloadLen == 1 {
|
||||
code = CloseCode.ProtocolError.rawValue
|
||||
} else if payloadLen > 1 {
|
||||
code = WebSocket.readUint16(buffer, offset: offset)
|
||||
code = WebSocket.readUint16(baseAddress, offset: offset)
|
||||
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
|
||||
code = CloseCode.ProtocolError.rawValue
|
||||
}
|
||||
@@ -524,7 +591,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if payloadLen > 2 {
|
||||
let len = Int(payloadLen-2)
|
||||
if len > 0 {
|
||||
let bytes = UnsafePointer<UInt8>((buffer+offset))
|
||||
let bytes = baseAddress + offset
|
||||
let str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
|
||||
if str == nil {
|
||||
code = CloseCode.ProtocolError.rawValue
|
||||
@@ -533,48 +600,44 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
doDisconnect(errorWithDetail("connection closed by server", code: code))
|
||||
writeError(code)
|
||||
return
|
||||
return emptyBuffer
|
||||
}
|
||||
if isControlFrame && payloadLen > 125 {
|
||||
writeError(CloseCode.ProtocolError.rawValue)
|
||||
return
|
||||
return emptyBuffer
|
||||
}
|
||||
var dataLength = UInt64(payloadLen)
|
||||
if dataLength == 127 {
|
||||
dataLength = WebSocket.readUint64(buffer, offset: offset)
|
||||
dataLength = WebSocket.readUint64(baseAddress, offset: offset)
|
||||
offset += sizeof(UInt64)
|
||||
} else if dataLength == 126 {
|
||||
dataLength = UInt64(WebSocket.readUint16(buffer, offset: offset))
|
||||
dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset))
|
||||
offset += sizeof(UInt16)
|
||||
}
|
||||
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
|
||||
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
||||
return
|
||||
fragBuffer = NSData(bytes: baseAddress, length: bufferLen)
|
||||
return emptyBuffer
|
||||
}
|
||||
var len = dataLength
|
||||
if dataLength > UInt64(bufferLen) {
|
||||
len = UInt64(bufferLen-offset)
|
||||
}
|
||||
var data: NSData!
|
||||
let data: NSData
|
||||
if len < 0 {
|
||||
len = 0
|
||||
data = NSData()
|
||||
} else {
|
||||
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
|
||||
data = NSData(bytes: baseAddress+offset, length: Int(len))
|
||||
}
|
||||
if receivedOpcode == .Pong {
|
||||
dispatch_async(queue) { [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.onPong?()
|
||||
s.pongDelegate?.websocketDidReceivePong(s)
|
||||
if canDispatch {
|
||||
dispatch_async(queue) { [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.onPong?()
|
||||
s.pongDelegate?.websocketDidReceivePong(s)
|
||||
}
|
||||
}
|
||||
|
||||
let step = Int(offset+numericCast(len))
|
||||
let extra = bufferLen-step
|
||||
if extra > 0 {
|
||||
processRawMessage((buffer+step), bufferLen: extra)
|
||||
}
|
||||
return
|
||||
return buffer.fromOffset(offset + Int(len))
|
||||
}
|
||||
var response = readStack.last
|
||||
if isControlFrame {
|
||||
@@ -584,7 +647,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
return emptyBuffer
|
||||
}
|
||||
var isNew = false
|
||||
if response == nil {
|
||||
@@ -593,7 +656,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
doDisconnect(errorWithDetail("first frame can't be a continue frame",
|
||||
code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
return emptyBuffer
|
||||
}
|
||||
isNew = true
|
||||
response = WSResponse()
|
||||
@@ -608,13 +671,13 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame",
|
||||
code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
return emptyBuffer
|
||||
}
|
||||
response!.buffer!.appendData(data)
|
||||
}
|
||||
if let response = response {
|
||||
response.bytesLeft -= Int(len)
|
||||
response.frameCount++
|
||||
response.frameCount += 1
|
||||
response.isFin = isFin > 0 ? true : false
|
||||
if isNew {
|
||||
readStack.append(response)
|
||||
@@ -623,20 +686,18 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
|
||||
let step = Int(offset+numericCast(len))
|
||||
let extra = bufferLen-step
|
||||
if extra > 0 {
|
||||
processExtra((buffer+step), bufferLen: extra)
|
||||
}
|
||||
return buffer.fromOffset(step)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
///process the extra of a buffer
|
||||
private func processExtra(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
||||
if bufferLen < 2 {
|
||||
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
||||
} else {
|
||||
processRawMessage(buffer, bufferLen: bufferLen)
|
||||
/// Process all messages in the buffer if possible.
|
||||
private func processRawMessagesInBuffer(pointer: UnsafePointer<UInt8>, bufferLen: Int) {
|
||||
var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen)
|
||||
repeat {
|
||||
buffer = processOneRawMessage(inBuffer: buffer)
|
||||
} while buffer.count >= 2
|
||||
if buffer.count > 0 {
|
||||
fragBuffer = NSData(buffer: buffer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -652,18 +713,21 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
writeError(CloseCode.Encoding.rawValue)
|
||||
return false
|
||||
}
|
||||
|
||||
dispatch_async(queue) { [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.onText?(str! as String)
|
||||
s.delegate?.websocketDidReceiveMessage(s, text: str! as String)
|
||||
if canDispatch {
|
||||
dispatch_async(queue) { [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.onText?(str! as String)
|
||||
s.delegate?.websocketDidReceiveMessage(s, text: str! as String)
|
||||
}
|
||||
}
|
||||
} else if response.code == .BinaryFrame {
|
||||
let data = response.buffer! //local copy so it is perverse for writing
|
||||
dispatch_async(queue) { [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.onData?(data)
|
||||
s.delegate?.websocketDidReceiveData(s, data: data)
|
||||
if canDispatch {
|
||||
let data = response.buffer! //local copy so it is perverse for writing
|
||||
dispatch_async(queue) { [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.onData?(data)
|
||||
s.delegate?.websocketDidReceiveData(s, data: data)
|
||||
}
|
||||
}
|
||||
}
|
||||
readStack.removeLast()
|
||||
@@ -687,9 +751,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
|
||||
}
|
||||
///used to write things to the stream
|
||||
private func dequeueWrite(data: NSData, code: OpCode) {
|
||||
guard isConnected else { return }
|
||||
|
||||
private func dequeueWrite(data: NSData, code: OpCode, writeCompletion: (() -> ())? = nil) {
|
||||
writeQueue.addOperationWithBlock { [weak self] in
|
||||
//stream isn't ready, let's wait
|
||||
guard let s = self else { return }
|
||||
@@ -721,9 +783,6 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
var total = 0
|
||||
while true {
|
||||
if !s.isConnected {
|
||||
break
|
||||
}
|
||||
guard let outStream = s.outputStream else { break }
|
||||
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
|
||||
let len = outStream.write(writeBuffer, maxLength: offset-total)
|
||||
@@ -741,6 +800,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
total += len
|
||||
}
|
||||
if total >= offset {
|
||||
if let queue = self?.queue, callback = writeCompletion {
|
||||
dispatch_async(queue) {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -751,242 +816,41 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
///used to preform the disconnect delegate
|
||||
private func doDisconnect(error: NSError?) {
|
||||
guard !didDisconnect else { return }
|
||||
|
||||
didDisconnect = true
|
||||
connected = false
|
||||
guard canDispatch else {return}
|
||||
dispatch_async(queue) { [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.didDisconnect = true
|
||||
s.onDisconnect?(error)
|
||||
s.delegate?.websocketDidDisconnect(s, error: error)
|
||||
let userInfo = error.map({ [WebsocketDisconnectionErrorKeyName: $0] })
|
||||
s.notificationCenter.postNotificationName(WebsocketDidDisconnectNotification, object: self, userInfo: userInfo)
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
mutex.lock()
|
||||
readyToWrite = false
|
||||
mutex.unlock()
|
||||
cleanupStream()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private class SSLCert {
|
||||
var certData: NSData?
|
||||
var key: SecKeyRef?
|
||||
private extension NSData {
|
||||
|
||||
/**
|
||||
Designated init for certificates
|
||||
|
||||
- parameter data: is the binary data of the certificate
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
init(data: NSData) {
|
||||
self.certData = data
|
||||
convenience init(buffer: UnsafeBufferPointer<UInt8>) {
|
||||
self.init(bytes: buffer.baseAddress, length: buffer.count)
|
||||
}
|
||||
|
||||
/**
|
||||
Designated init for public keys
|
||||
|
||||
- parameter key: is the public key to be used
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
init(key: SecKeyRef) {
|
||||
self.key = key
|
||||
}
|
||||
}
|
||||
|
||||
private class SSLSecurity {
|
||||
var validatedDN = true //should the domain name be validated?
|
||||
private extension UnsafeBufferPointer {
|
||||
|
||||
var isReady = false //is the key processing done?
|
||||
var certificates: [NSData]? //the certificates
|
||||
var pubKeys: [SecKeyRef]? //the public keys
|
||||
var usePublicKeys = false //use public keys or certificate validation?
|
||||
|
||||
/**
|
||||
Use certs from main app bundle
|
||||
|
||||
- parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
convenience init(usePublicKeys: Bool = false) {
|
||||
let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".")
|
||||
|
||||
let certs = paths.reduce([SSLCert]()) { (var certs: [SSLCert], path: String) -> [SSLCert] in
|
||||
if let data = NSData(contentsOfFile: path) {
|
||||
certs.append(SSLCert(data: data))
|
||||
}
|
||||
return certs
|
||||
}
|
||||
|
||||
self.init(certs: certs, usePublicKeys: usePublicKeys)
|
||||
func fromOffset(offset: Int) -> UnsafeBufferPointer<Element> {
|
||||
return UnsafeBufferPointer<Element>(start: baseAddress.advancedBy(offset), count: count - offset)
|
||||
}
|
||||
|
||||
/**
|
||||
Designated init
|
||||
|
||||
- parameter keys: is the certificates or public keys to use
|
||||
- parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
init(certs: [SSLCert], usePublicKeys: Bool) {
|
||||
self.usePublicKeys = usePublicKeys
|
||||
|
||||
if self.usePublicKeys {
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) {
|
||||
let pubKeys = certs.reduce([SecKeyRef]()) { (var pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in
|
||||
if let data = cert.certData where cert.key == nil {
|
||||
cert.key = self.extractPublicKey(data)
|
||||
}
|
||||
if let key = cert.key {
|
||||
pubKeys.append(key)
|
||||
}
|
||||
return pubKeys
|
||||
}
|
||||
|
||||
self.pubKeys = pubKeys
|
||||
self.isReady = true
|
||||
}
|
||||
} else {
|
||||
let certificates = certs.reduce([NSData]()) { (var certificates: [NSData], cert: SSLCert) -> [NSData] in
|
||||
if let data = cert.certData {
|
||||
certificates.append(data)
|
||||
}
|
||||
return certificates
|
||||
}
|
||||
self.certificates = certificates
|
||||
self.isReady = true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Valid the trust and domain name.
|
||||
|
||||
- parameter trust: is the serverTrust to validate
|
||||
- parameter domain: is the CN domain to validate
|
||||
|
||||
- returns: if the key was successfully validated
|
||||
*/
|
||||
func isValid(trust: SecTrustRef, domain: String?) -> Bool {
|
||||
|
||||
var tries = 0
|
||||
while(!self.isReady) {
|
||||
usleep(1000)
|
||||
tries += 1
|
||||
if tries > 5 {
|
||||
return false //doesn't appear it is going to ever be ready...
|
||||
}
|
||||
}
|
||||
var policy: SecPolicyRef
|
||||
if self.validatedDN {
|
||||
policy = SecPolicyCreateSSL(true, domain)
|
||||
} else {
|
||||
policy = SecPolicyCreateBasicX509()
|
||||
}
|
||||
SecTrustSetPolicies(trust,policy)
|
||||
if self.usePublicKeys {
|
||||
if let keys = self.pubKeys {
|
||||
let serverPubKeys = publicKeyChainForTrust(trust)
|
||||
for serverKey in serverPubKeys as [AnyObject] {
|
||||
for key in keys as [AnyObject] {
|
||||
if serverKey.isEqual(key) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if let certs = self.certificates {
|
||||
let serverCerts = certificateChainForTrust(trust)
|
||||
var collect = [SecCertificate]()
|
||||
for cert in certs {
|
||||
collect.append(SecCertificateCreateWithData(nil,cert)!)
|
||||
}
|
||||
SecTrustSetAnchorCertificates(trust,collect)
|
||||
var result: SecTrustResultType = 0
|
||||
SecTrustEvaluate(trust,&result)
|
||||
let r = Int(result)
|
||||
if r == kSecTrustResultUnspecified || r == kSecTrustResultProceed {
|
||||
var trustedCount = 0
|
||||
for serverCert in serverCerts {
|
||||
for cert in certs {
|
||||
if cert == serverCert {
|
||||
trustedCount++
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if trustedCount == serverCerts.count {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
Get the public key from a certificate data
|
||||
|
||||
- parameter data: is the certificate to pull the public key from
|
||||
|
||||
- returns: a public key
|
||||
*/
|
||||
func extractPublicKey(data: NSData) -> SecKeyRef? {
|
||||
guard let cert = SecCertificateCreateWithData(nil, data) else { return nil }
|
||||
|
||||
return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509())
|
||||
}
|
||||
|
||||
/**
|
||||
Get the public key from a certificate
|
||||
|
||||
- parameter data: is the certificate to pull the public key from
|
||||
|
||||
- returns: a public key
|
||||
*/
|
||||
func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? {
|
||||
var possibleTrust: SecTrust?
|
||||
SecTrustCreateWithCertificates(cert, policy, &possibleTrust)
|
||||
|
||||
guard let trust = possibleTrust else { return nil }
|
||||
|
||||
var result: SecTrustResultType = 0
|
||||
SecTrustEvaluate(trust, &result)
|
||||
return SecTrustCopyPublicKey(trust)
|
||||
}
|
||||
|
||||
/**
|
||||
Get the certificate chain for the trust
|
||||
|
||||
- parameter trust: is the trust to lookup the certificate chain for
|
||||
|
||||
- returns: the certificate chain for the trust
|
||||
*/
|
||||
func certificateChainForTrust(trust: SecTrustRef) -> [NSData] {
|
||||
let certificates = (0..<SecTrustGetCertificateCount(trust)).reduce([NSData]()) { (var certificates: [NSData], index: Int) -> [NSData] in
|
||||
let cert = SecTrustGetCertificateAtIndex(trust, index)
|
||||
certificates.append(SecCertificateCopyData(cert!))
|
||||
return certificates
|
||||
}
|
||||
|
||||
return certificates
|
||||
}
|
||||
|
||||
/**
|
||||
Get the public key chain for the trust
|
||||
|
||||
- parameter trust: is the trust to lookup the certificate chain and extract the public keys
|
||||
|
||||
- returns: the public keys from the certifcate chain for the trust
|
||||
*/
|
||||
func publicKeyChainForTrust(trust: SecTrustRef) -> [SecKeyRef] {
|
||||
let policy = SecPolicyCreateBasicX509()
|
||||
let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKeyRef]()) { (var keys: [SecKeyRef], index: Int) -> [SecKeyRef] in
|
||||
let cert = SecTrustGetCertificateAtIndex(trust, index)
|
||||
if let key = extractPublicKeyFromCert(cert!, policy: policy) {
|
||||
keys.append(key)
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
|
||||
Reference in new issue
Block a user