Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0579e7ec19 | ||
|
|
aee0382cbc | ||
|
|
9abf2e77e0 | ||
|
|
0dd3def2e4 | ||
|
|
c5d70b4888 | ||
|
|
ee38630468 | ||
|
|
5a65efe526 | ||
|
|
02971e14c2 | ||
|
|
ea7e60cde2 | ||
|
|
83cee796d8 | ||
|
|
86bd271a9f | ||
|
|
6e31f54e88 | ||
|
|
b97574e28a | ||
|
|
ab56b58b2d | ||
|
|
8e2f478989 | ||
|
|
c99f9a6b97 | ||
|
|
45b5852e50 | ||
|
|
c608bf8286 | ||
|
|
6c6084705e | ||
|
|
885965c5bc | ||
|
|
ac228ccede | ||
|
|
7bc8cd01e8 | ||
|
|
b9e05286a2 | ||
|
|
a5db43b834 | ||
|
|
7382030dff | ||
|
|
40ac53844d | ||
|
|
7f443faf92 | ||
|
|
a6c700230d | ||
|
|
aa368f92cf | ||
|
|
28ae7a8240 | ||
|
|
e07ed93c0b | ||
|
|
17fb142083 | ||
|
|
66674aae78 | ||
|
|
395dc48287 | ||
|
|
1648a51b6f | ||
|
|
ad7043c918 | ||
|
|
48672d8df3 | ||
|
|
d657538214 | ||
|
|
a231104c15 | ||
|
|
ab8de6932c | ||
|
|
c101a04845 | ||
|
|
3d06b7dbad | ||
|
|
f57786ad5b | ||
|
|
7ff1d327de | ||
|
|
99e2da235a | ||
|
|
a20a0f14f3 | ||
|
|
0e478085a3 | ||
|
|
61eda5971e | ||
|
|
32e1f55394 | ||
|
|
a88a859750 | ||
|
|
aaefdd0a2e | ||
|
|
4c7a09cc8e | ||
|
|
90c7c9aadc | ||
|
|
84499d4c21 | ||
|
|
bfe54f8df7 | ||
|
|
18a227e591 | ||
|
|
6d49c37fb8 | ||
|
|
a0c213364d | ||
|
|
3c79bd0a75 | ||
|
|
a11533b61f | ||
|
|
8acd32324e | ||
|
|
b65dfec6b0 | ||
|
|
1e07070798 | ||
|
|
927ab155e3 | ||
|
|
de20099c07 | ||
|
|
877db516c2 | ||
|
|
4dd882b8ad | ||
|
|
ccc3745bb8 | ||
|
|
718dc27089 | ||
|
|
798d8a62ae | ||
|
|
9241bf869f | ||
|
|
7573355731 | ||
|
|
f3b4c0eba3 | ||
|
|
d2f39b163a | ||
|
|
b8ab80bdf1 | ||
|
|
66455f3e1b | ||
|
|
5d867f4f65 | ||
|
|
166d59341c | ||
|
|
1ad87bdb0d | ||
|
|
14dc5957fc | ||
|
|
c757ede90e | ||
|
|
e99030846f | ||
|
|
3f8941d35b | ||
|
|
a005646054 | ||
|
|
3025911502 | ||
|
|
3791b9c112 | ||
|
|
39135c089b | ||
|
|
bd5e2db98a | ||
|
|
4531d2e1a1 | ||
|
|
5772f8fb4f | ||
|
|
b336f0e267 | ||
|
|
d647c53122 | ||
|
|
f933b7addc | ||
|
|
288c04e629 | ||
|
|
3754cd2c2d | ||
|
|
20b28b2f43 | ||
|
|
a5d40c4479 | ||
|
|
31fbe1040d | ||
|
|
c0afc006e3 | ||
|
|
fe0d5d835f | ||
|
|
ded625aaef | ||
|
|
54e0b6c189 | ||
|
|
72ed7d4be8 | ||
|
|
b9c01ce614 | ||
|
|
faaa0473d9 | ||
|
|
195f04c982 | ||
|
|
0eeecd84ce | ||
|
|
4ae6489230 | ||
|
|
0ebbf3f0cd | ||
|
|
12b312de57 | ||
|
|
bb518ac1a4 | ||
|
|
13176f149c | ||
|
|
3e53228e36 | ||
|
|
e2cd910fa7 | ||
|
|
21ac65733f | ||
|
|
6ab7455a08 | ||
|
|
7a146bf6ac | ||
|
|
0d7d319cc3 | ||
|
|
14b0022fdc | ||
|
|
9c16ffade8 | ||
|
|
30c1a4df97 | ||
|
|
492ae89344 | ||
|
|
7bdf80d133 | ||
|
|
01b88f8e37 | ||
|
|
9860452814 | ||
|
|
835e1c2262 | ||
|
|
ba7ffe6d26 | ||
|
|
6ed90a3e60 | ||
|
|
d2d9c49414 | ||
|
|
4c033f81d6 | ||
|
|
b0cf8d2c40 | ||
|
|
1a48adb03d | ||
|
|
9a39524ba2 | ||
|
|
5b6b36a2dc | ||
|
|
198f24c684 | ||
|
|
f464eba995 | ||
|
|
0e791176bd | ||
|
|
243a750377 | ||
|
|
6cffbc2404 | ||
|
|
a56227d08a | ||
|
|
0233bce881 | ||
|
|
456406416a | ||
|
|
99ed93038f | ||
|
|
9a05f6043b | ||
|
|
70c7dacde9 | ||
|
|
a9b4193fe4 | ||
|
|
aaaf9dc451 | ||
|
|
fe8469cfc6 | ||
|
|
f5c3a2cac9 | ||
|
|
7d26bd3ee8 | ||
|
|
136847fd77 | ||
|
|
9b3f84dcd0 | ||
|
|
a72f96759e | ||
|
|
a81f925671 | ||
|
|
4997294186 | ||
|
|
ba5638a109 | ||
|
|
978bd2614e | ||
|
|
2f2bd49045 | ||
|
|
f889d37e9b | ||
|
|
67afbcbd56 | ||
|
|
d0a57ca353 | ||
|
|
9355fc5077 | ||
|
|
fd21ca00d3 | ||
|
|
f818d64405 | ||
|
|
55289d69a3 | ||
|
|
5dc0dfa9aa | ||
|
|
2e7be97a38 | ||
|
|
60e0142955 | ||
|
|
e84acb1471 | ||
|
|
8044d6fc1c | ||
|
|
e3ff1f434b | ||
|
|
ca67e9e47e | ||
|
|
108aa4b08a | ||
|
|
f5f2a15133 | ||
|
|
ec76704631 | ||
|
|
2e9232365d | ||
|
|
a91fc638f2 | ||
|
|
e634b131fb | ||
|
|
0e0d47b6ed | ||
|
|
4009e577b7 | ||
|
|
bee997aff4 | ||
|
|
f82aafd5c8 | ||
|
|
07f9d4f548 | ||
|
|
17444dd4a3 | ||
|
|
6a10f72443 | ||
|
|
c6997f32dd | ||
|
|
e955699b21 | ||
|
|
2bb7360918 | ||
|
|
d5b9afd28d | ||
|
|
adb3650609 | ||
|
|
dc50af1505 | ||
|
|
bad0d4b419 | ||
|
|
b8cfdc8fd2 | ||
|
|
a43548e203 | ||
|
|
2bc72e1975 | ||
|
|
1739afa670 | ||
|
|
40d76cdbeb | ||
|
|
4f2040fbfd | ||
|
|
d2ae3705ff | ||
|
|
a634f5bacc | ||
|
|
259e543ad5 | ||
|
|
713ce46e3b | ||
|
|
44508a5193 | ||
|
|
80cfe8c534 | ||
|
|
8320e296e9 | ||
|
|
31a2079222 | ||
|
|
c9d26ebd65 | ||
|
|
77e1da2b51 | ||
|
|
8a911a871e | ||
|
|
d8c8b4941e | ||
|
|
520a765c22 | ||
|
|
5d9a8e88bf | ||
|
|
ec200e78bb | ||
|
|
70b06a2248 | ||
|
|
6cdacefdec | ||
|
|
222f622d3a | ||
|
|
91cc683b5b | ||
|
|
12f607e3c3 | ||
|
|
568b2ae1bc | ||
|
|
c8c67d66a8 | ||
|
|
70cacb025f | ||
|
|
5fdea20455 | ||
|
|
2bd612e47a | ||
|
|
fb9b19820b | ||
|
|
8bae7d06d2 | ||
|
|
0b8be08a54 | ||
|
|
6f16694ed2 | ||
|
|
13087ff1b7 | ||
|
|
648d9d9df0 | ||
|
|
16ed2bd130 | ||
|
|
de0d0b8676 | ||
|
|
e79199d2e6 | ||
|
|
ac023013d4 | ||
|
|
0cfdd0b005 | ||
|
|
f32c0850ac | ||
|
|
fe7fb3ea4e | ||
|
|
4de0652568 | ||
|
|
6e43e58988 | ||
|
|
d6e1510cbf | ||
|
|
13440ce6b1 | ||
|
|
d81cbd7d24 | ||
|
|
a147ebcd85 | ||
|
|
8d0af14f04 | ||
|
|
0ff4cb9713 | ||
|
|
2ae994a031 | ||
|
|
0dc4f863f3 | ||
|
|
0fb9be6247 | ||
|
|
69b3958796 | ||
|
|
110a6748ab | ||
|
|
e238293711 | ||
|
|
dfc905d9c3 | ||
|
|
530e6f8f9d | ||
|
|
7bf1a40c54 | ||
|
|
e91f1031d6 | ||
|
|
adf8536c0c | ||
|
|
c1f80dc0c5 | ||
|
|
1777d490c5 | ||
|
|
5471411f74 | ||
|
|
cd2ee8950f | ||
|
|
672e3601ed | ||
|
|
f3ed05e970 | ||
|
|
e19a28684b | ||
|
|
39a7a4f337 | ||
|
|
3234b71b5b | ||
|
|
80d7622095 | ||
|
|
8dc7121355 | ||
|
|
17426c1432 | ||
|
|
5a73a5e6da | ||
|
|
1f5402ce1c | ||
|
|
9510ef9d4f | ||
|
|
2a7ec38d48 | ||
|
|
ccd6dcbf0a | ||
|
|
4fdb49ea2f | ||
|
|
2351637ab4 | ||
|
|
58097fa39e | ||
|
|
4c9d6ef3de | ||
|
|
aa43107ad6 | ||
|
|
46cea36df7 | ||
|
|
9c3d991bed | ||
|
|
6ee1daeaf7 | ||
|
|
09a26c0b1c | ||
|
|
f752507a11 | ||
|
|
2cafec6f12 | ||
|
|
7ebcd7439f | ||
|
|
5e92fc323d | ||
|
|
c2b927fd02 | ||
|
|
4014286da2 | ||
|
|
884b73c777 | ||
|
|
b563334d14 | ||
|
|
848f7e5da7 | ||
|
|
0fd8a9540b | ||
|
|
42aced5e9c | ||
|
|
b52684cb8f | ||
|
|
25464ffb9d | ||
|
|
d0f091e983 | ||
|
|
889ad404bc | ||
|
|
6fa7636261 | ||
|
|
5eeac96b2b | ||
|
|
f46629f850 | ||
|
|
84bb6b7dad | ||
|
|
145448c087 | ||
|
|
184b97ef8c | ||
|
|
d0ec1de566 | ||
|
|
643ddb5bf9 | ||
|
|
469caf1b54 | ||
|
|
c38412cae6 | ||
|
|
8bde261acb | ||
|
|
9b9becebae | ||
|
|
63a257ac80 | ||
|
|
514193e6ec | ||
|
|
969e6d6ea8 | ||
|
|
ffbe1e4ec4 | ||
|
|
80ea42c91f | ||
|
|
0308e274cd | ||
|
|
dd71d4954d | ||
|
|
06e2311acc | ||
|
|
2579c04f67 | ||
|
|
137fd1229b | ||
|
|
6650afd3e4 | ||
|
|
150e26aefd | ||
|
|
f0a45e13e2 | ||
|
|
7800591367 | ||
|
|
92367fc796 | ||
|
|
fbe3bd9b30 | ||
|
|
e25afd60fd | ||
|
|
f0b4f077d4 | ||
|
|
1b08411ed4 | ||
|
|
bf3e28df81 | ||
|
|
4086ce7d75 | ||
|
|
feea80a2f9 | ||
|
|
a0e3052893 | ||
|
|
79848b1ce0 | ||
|
|
30cf2bb67a | ||
|
|
b1b9a7edaf | ||
|
|
cf98f09b93 | ||
|
|
e792006245 | ||
|
|
3c9c473e70 | ||
|
|
252181b0c5 | ||
|
|
a4988e6404 | ||
|
|
a1af98e173 | ||
|
|
aa6db7c837 | ||
|
|
a07916fb2f | ||
|
|
4b9db85a49 | ||
|
|
149e6137af | ||
|
|
224c660e4c | ||
|
|
7b795fd989 | ||
|
|
67f57daaab | ||
|
|
846f10eb13 | ||
|
|
11730b5fcd | ||
|
|
47a839b934 | ||
|
|
94a3844181 | ||
|
|
01aa6354e3 | ||
|
|
ac663a8875 | ||
|
|
a277e88c3b | ||
|
|
fba226a6de | ||
|
|
d073fa8a83 | ||
|
|
8928ce2693 | ||
|
|
5057226a6c | ||
|
|
ebe9384604 | ||
|
|
5f75e6080b | ||
|
|
c40b7c169f | ||
|
|
ea0fc9933e | ||
|
|
c21799abac | ||
|
|
43827914b7 | ||
|
|
22b9a1e2f2 | ||
|
|
fd66a9fa62 | ||
|
|
68078e50d5 | ||
|
|
8daa7da426 | ||
|
|
24583f19c1 | ||
|
|
652c81a80e | ||
|
|
422b93f577 | ||
|
|
998089df91 | ||
|
|
283644b75c | ||
|
|
38a7cc8648 | ||
|
|
a22869efad | ||
|
|
6ecd1e2a79 | ||
|
|
846897157c | ||
|
|
a49f8f19cf | ||
|
|
b388df798b | ||
|
|
531a9784da | ||
|
|
c34a660cae | ||
|
|
9484bc9614 | ||
|
|
7206fa6d5c | ||
|
|
362f4e90b8 | ||
|
|
d8f65c2804 | ||
|
|
ca3f3e810d | ||
|
|
77eb1603ac | ||
|
|
63021eb995 | ||
|
|
eb00be0aaa | ||
|
|
d8e3408565 | ||
|
|
9454a47ef4 | ||
|
|
bd88ff763b | ||
|
|
f41b64137e | ||
|
|
df2f149f85 | ||
|
|
f2ef3344c0 | ||
|
|
65be52418d | ||
|
|
76637d160e | ||
|
|
f17575b35c | ||
|
|
f2e5a1437b | ||
|
|
a0c676bc54 | ||
|
|
5854262280 | ||
|
|
1c8fcee772 | ||
|
|
11d8430537 | ||
|
|
a15b57e900 | ||
|
|
fafeebe185 | ||
|
|
66622fffb3 | ||
|
|
7bf35e182c | ||
|
|
78727dc0ee |
No files matched your search
+21
@@ -1,6 +1,7 @@
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
*.xcodeproj
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
@@ -23,3 +24,23 @@ Icon
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
# Xcode
|
||||
build/
|
||||
*.pbxuser
|
||||
!default.pbxuser
|
||||
*.mode1v3
|
||||
!default.mode1v3
|
||||
*.mode2v3
|
||||
!default.mode2v3
|
||||
*.perspectivev3
|
||||
!default.perspectivev3
|
||||
xcuserdata
|
||||
*.xccheckout
|
||||
*.moved-aside
|
||||
DerivedData
|
||||
*.hmap
|
||||
*.ipa
|
||||
*.xcuserstate
|
||||
|
||||
Socket.IO-Test-Server/node_modules/*
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
language: objective-c
|
||||
xcode_project: Socket.IO-Client-Swift.xcodeproj # path to your xcodeproj folder
|
||||
xcode_scheme: SocketIO-iOS
|
||||
osx_image: xcode7
|
||||
before_install:
|
||||
- cd Socket.IO-Test-Server/
|
||||
- npm install
|
||||
- cd ..
|
||||
install: node Socket.IO-Test-Server/main.js &
|
||||
script: xctool -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac build test -parallelize
|
||||
cache:
|
||||
directories:
|
||||
- Socket.IO-Test-Server/node_modules
|
||||
@@ -1,21 +1,23 @@
|
||||
[](https://travis-ci.org/socketio/socket.io-client-swift)
|
||||
|
||||
#Socket.IO-Client-Swift
|
||||
Socket.IO-client for iOS/OS X.
|
||||
|
||||
##Example
|
||||
```swift
|
||||
let socket = SocketIOClient(socketURL: "localhost:8080")
|
||||
let socket = SocketIOClient(socketURL: "localhost:8080", options: [.Log(true), .ForcePolling(true)])
|
||||
|
||||
socket.on("connect") {data, ack in
|
||||
println("socket connected")
|
||||
print("socket connected")
|
||||
}
|
||||
|
||||
socket.on("currentAmount") {data, ack in
|
||||
if let cur = data?[0] as? Double {
|
||||
socket.emitWithAck("canUpdate", cur)(timeout: 0) {data in
|
||||
if let cur = data[0] as? Double {
|
||||
socket.emitWithAck("canUpdate", cur)(timeoutAfter: 0) {data in
|
||||
socket.emit("update", ["amount": cur + 2.50])
|
||||
}
|
||||
|
||||
ack?("Got your currentAmount", "dude")
|
||||
ack?.with("Got your currentAmount", "dude")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,20 +26,20 @@ socket.connect()
|
||||
|
||||
##Objective-C Example
|
||||
```objective-c
|
||||
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" options:nil];
|
||||
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" options:@{@"log": @YES, @"forcePolling": @YES}];
|
||||
|
||||
[socket on:@"connect" callback:^(NSArray* data, void (^ack)(NSArray*)) {
|
||||
[socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
|
||||
NSLog(@"socket connected");
|
||||
}];
|
||||
|
||||
[socket on:@"currentAmount" callback:^(NSArray* data, void (^ack)(NSArray*)) {
|
||||
[socket on:@"currentAmount" callback:^(NSArray* data, SocketAckEmitter* ack) {
|
||||
double cur = [[data objectAtIndex:0] floatValue];
|
||||
|
||||
[socket emitWithAck:@"canUpdate" withItems:@[@(cur)]](0, ^(NSArray* data) {
|
||||
[socket emit:@"update" withItems:@[@{@"amount": @(cur + 2.50)}]];
|
||||
});
|
||||
|
||||
ack(@[@"Got your currentAmount, ", @"dude"]);
|
||||
[ack with:@[@"Got your currentAmount, ", @"dude"]];
|
||||
}];
|
||||
|
||||
[socket connect];
|
||||
@@ -52,14 +54,26 @@ SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8
|
||||
- Can be used from Objective-C
|
||||
|
||||
##Installation
|
||||
Requires Swift 1.2/Xcode 6.3
|
||||
Requires Swift 2/Xcode 7
|
||||
|
||||
If you need Swift 1.2/Xcode 6.3/4 use v2.4.5 (Pre-Swift 2 support is no longer maintained)
|
||||
|
||||
If you need Swift 1.1/Xcode 6.2 use v1.5.2. (Pre-Swift 1.2 support is no longer maintained)
|
||||
|
||||
Manually (iOS 7+)
|
||||
-----------------
|
||||
1. Copy the SocketIOClientSwift folder into your Xcode project. (Make sure you add the files to your target(s))
|
||||
2. If you plan on using this from Objective-C, read [this](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html) on exposing Swift code to Objective-C.
|
||||
|
||||
Carthage
|
||||
-----------------
|
||||
Add this line to your `Cartfile`:
|
||||
```
|
||||
github "socketio/socket.io-client-swift" ~> 4.0.3 # Or latest version
|
||||
```
|
||||
|
||||
Run `carthage update --platform ios,macosx`.
|
||||
|
||||
CocoaPods 0.36.0 or later (iOS 8+)
|
||||
------------------
|
||||
Create `Podfile` and add `pod 'Socket.IO-Client-Swift'`:
|
||||
@@ -69,7 +83,7 @@ source 'https://github.com/CocoaPods/Specs.git'
|
||||
platform :ios, '8.0'
|
||||
use_frameworks!
|
||||
|
||||
pod 'Socket.IO-Client-Swift', '~> 1.3.2' # Or latest version
|
||||
pod 'Socket.IO-Client-Swift', '~> 4.0.3' # Or latest version
|
||||
```
|
||||
|
||||
Install pods:
|
||||
@@ -78,47 +92,75 @@ Install pods:
|
||||
$ pod install
|
||||
```
|
||||
|
||||
Import in your swift file:
|
||||
Import the module:
|
||||
|
||||
Swift:
|
||||
```swift
|
||||
import Socket_IO_Client_Swift
|
||||
```
|
||||
|
||||
Objective-C:
|
||||
|
||||
```Objective-C
|
||||
#import <Socket_IO_Client_Swift/Socket_IO_Client_Swift-Swift.h>
|
||||
```
|
||||
|
||||
CocoaSeeds
|
||||
-----------------
|
||||
|
||||
Add this line to your `Seedfile`:
|
||||
|
||||
```
|
||||
github "socketio/socket.io-client-swift", "v4.0.3", :files => "SocketIOClientSwift/*.swift" # Or latest version
|
||||
```
|
||||
|
||||
Run `seed install`.
|
||||
|
||||
|
||||
##API
|
||||
Constructors
|
||||
-----------
|
||||
`init(socketURL: String, opts:NSDictionary? = nil)` - Constructs a new client for the given URL. opts can be omitted (will use default values)
|
||||
`init(var socketURL: String, options: Set<SocketIOClientOption>? = nil)` - 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.
|
||||
|
||||
`convenience init(socketURL: String, options:NSDictionary?)` - Same as above, but meant for Objective-C. See Objective-C Example.
|
||||
`convenience init(socketURL: String, options: NSDictionary?)` - Same as above, but meant for Objective-C. See Options on how convert between SocketIOClientOptions and dictionary keys.
|
||||
|
||||
Options
|
||||
-------
|
||||
- `connectParams: [String: AnyObject]?` - Dictionary whose contents will be passed with the connection.
|
||||
- `reconnects: Bool` Default is `true`
|
||||
- `reconnectAttempts: Int` Default is `-1` (infinite tries)
|
||||
- `reconnectWait: Int` Default is `10`
|
||||
- `forcePolling: Bool` Default is `false`. `true` forces the client to use xhr-polling.
|
||||
- `forceWebsockets: Bool` Default is `false`. `true` forces the client to use WebSockets.
|
||||
- `nsp: String` Default is `"/"`. Connects to a namespace.
|
||||
- `cookies: [NSHTTPCookie]?` An array of NSHTTPCookies. Passed during the handshake. Default is nil.
|
||||
- `log: Bool` If `true` socket will log debug messages. Default is false.
|
||||
- `sessionDelegate: NSURLSessionDelegate` Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
|
||||
- `path: String` - If the server uses a custom path. ex: `"/swift"`. Default is `""`
|
||||
All options are a case of SocketIOClientOption. To get the Objective-C Option, convert the name to lowerCamelCase.
|
||||
|
||||
```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 ForcePolling(Bool) // `true` forces the client to use xhr-polling. Default is `false`
|
||||
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 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 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.
|
||||
```
|
||||
Methods
|
||||
-------
|
||||
1. `on(name:String, callback:((data:NSArray?, ack:AckEmitter?) -> Void))` - Adds a handler for an event. Items are passed by an array. `ack` can be used to send an ack when one is requested. See example.
|
||||
2. `onAny(callback:((event:String, items:AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
|
||||
3. `emit(event:String, _ items:AnyObject...)` - Sends a message. Can send multiple items.
|
||||
4. `emit(event:String, withItems items:[AnyObject])` - `emit` for Objective-C
|
||||
5. `emitWithAck(event:String, _ items:AnyObject...) -> (timeout:UInt64, callback:(NSArray?) -> Void) -> Void` - Sends a message that requests an acknowledgement from the server. Returns a function which you can use to add a handler. See example. Note: The message is not sent until you call the returned function.
|
||||
6. `emitWithAck(event:String, withItems items:[AnyObject]) -> (UInt64, (NSArray?) -> Void) -> Void` - `emitWithAck` for Objective-C. Note: The message is not sent until you call the returned function.
|
||||
7. `connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
|
||||
8. `connect(#timeoutAfter:Int, withTimeoutHandler handler:(() -> Void)?)` - Connect to the server. If it isn't connected after timeoutAfter seconds, the handler is called.
|
||||
9. `close(#fast:Bool)` - Closes the socket. Once a socket is closed it should not be reopened. Pass true to fast if you're closing from a background task.
|
||||
10. `reconnect()` - Causes the client to reconnect to the server.
|
||||
11. `joinNamespace()` - Causes the client to join nsp. Shouldn't need to be called unless you change nsp manually.
|
||||
12. `leaveNamespace()` - Causes the client to leave the nsp and go back to /
|
||||
1. `on(event: String, callback: NormalCallback)` - Adds a handler for an event. Items are passed by an array. `ack` can be used to send an ack when one is requested. See example.
|
||||
2. `once(event: String, callback: NormalCallback)` - Adds a handler that will only be executed once.
|
||||
3. `onAny(callback:((event: String, items: AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
|
||||
4. `emit(event: String, _ items: AnyObject...)` - Sends a message. Can send multiple items.
|
||||
5. `emit(event: String, withItems items: [AnyObject])` - `emit` for Objective-C
|
||||
6. `emitWithAck(event: String, _ items: AnyObject...) -> (timeoutAfter: UInt64, callback: (NSArray?) -> Void) -> Void` - Sends a message that requests an acknowledgement from the server. Returns a function which you can use to add a handler. See example. Note: The message is not sent until you call the returned function.
|
||||
7. `emitWithAck(event: String, withItems items: [AnyObject]) -> (UInt64, (NSArray?) -> Void) -> Void` - `emitWithAck` for Objective-C. Note: The message is not sent until you call the returned function.
|
||||
8. `connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
|
||||
9. `connect(timeoutAfter timeoutAfter: Int, withTimeoutHandler handler: (() -> Void)?)` - Connect to the server. If it isn't connected after timeoutAfter seconds, the handler is called.
|
||||
10. `close()` - Closes the socket. Once a socket is closed it should not be reopened.
|
||||
11. `reconnect()` - Causes the client to reconnect to the server.
|
||||
12. `joinNamespace()` - Causes the client to join nsp. Shouldn't need to be called unless you change nsp manually.
|
||||
13. `leaveNamespace()` - Causes the client to leave the nsp and go back to /
|
||||
14. `off(event: String)` - Removes all event handlers for event.
|
||||
15. `removeAllHandlers()` - Removes all handlers.
|
||||
|
||||
Client Events
|
||||
------
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "Socket.IO-Client-Swift"
|
||||
s.version = "2.3.4"
|
||||
s.version = "4.0.3"
|
||||
s.summary = "Socket.IO-client for iOS and OS X"
|
||||
s.description = <<-DESC
|
||||
Socket.IO-client for iOS and OS X.
|
||||
@@ -12,7 +12,7 @@ Pod::Spec.new do |s|
|
||||
s.author = { "Erik" => "nuclear.ace@gmail.com" }
|
||||
s.ios.deployment_target = '8.0'
|
||||
s.osx.deployment_target = '10.10'
|
||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v2.3.4' }
|
||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v4.0.3' }
|
||||
s.source_files = "SocketIOClientSwift/**/*.swift"
|
||||
s.requires_arc = true
|
||||
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+7
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "self:Socket.IO-Client-Swift.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
@@ -0,0 +1,113 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0640"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-Mac"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2411B51F18A00EEBB58"
|
||||
BuildableName = "SocketIO-MacTests.xctest"
|
||||
BlueprintName = "SocketIO-MacTests"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2411B51F18A00EEBB58"
|
||||
BuildableName = "SocketIO-MacTests.xctest"
|
||||
BlueprintName = "SocketIO-MacTests"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-Mac"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-Mac"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-Mac"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,114 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0640"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-iOS"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2231B51F16C00EEBB58"
|
||||
BuildableName = "SocketIO-iOSTests.xctest"
|
||||
BlueprintName = "SocketIO-iOSTests"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2231B51F16C00EEBB58"
|
||||
BuildableName = "SocketIO-iOSTests.xctest"
|
||||
BlueprintName = "SocketIO-iOSTests"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-iOS"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-iOS"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-iOS"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,95 @@
|
||||
var assert = require("assert")
|
||||
|
||||
module.exports = {
|
||||
basicTest: {
|
||||
assert: function(inputData) {
|
||||
|
||||
},
|
||||
returnData: []
|
||||
},
|
||||
testNull: {
|
||||
assert: function(inputData) {
|
||||
assert(!inputData)
|
||||
},
|
||||
returnData: [null]
|
||||
},
|
||||
testBinary: {
|
||||
assert: function(inputData) {
|
||||
assert.equal(inputData.toString(), "gakgakgak2")
|
||||
},
|
||||
returnData: [new Buffer("gakgakgak2", "utf-8")]
|
||||
},
|
||||
testArray: {
|
||||
assert: function(inputData) {
|
||||
assert.equal(inputData.length, 2)
|
||||
assert.equal(inputData[0], "test1")
|
||||
assert.equal(inputData[1], "test2")
|
||||
},
|
||||
returnData: [["test3", "test4"]]
|
||||
},
|
||||
testString: {
|
||||
assert: function(inputData) {
|
||||
assert.equal(inputData, "marco")
|
||||
},
|
||||
returnData: ["polo"]
|
||||
},
|
||||
testBool: {
|
||||
assert: function(inputData) {
|
||||
assert(!inputData)
|
||||
},
|
||||
returnData: [true]
|
||||
},
|
||||
testInteger: {
|
||||
assert: function(inputData) {
|
||||
assert.equal(inputData, 10)
|
||||
},
|
||||
returnData: [20]
|
||||
},
|
||||
testDouble: {
|
||||
assert: function(inputData) {
|
||||
assert.equal(inputData, 1.1)
|
||||
},
|
||||
returnData: [1.2]
|
||||
},
|
||||
testJSON: {
|
||||
assert: function(inputData) {
|
||||
assert.equal(inputData.name, "test")
|
||||
assert.equal(inputData.nestedTest.test, "test")
|
||||
assert.equal(inputData.testArray.length, 1)
|
||||
},
|
||||
returnData: [{testString: "test", testNumber: 15, nestedTest: {test: "test"}, testArray: [1, 1]}]
|
||||
},
|
||||
testJSONWithBuffer: {
|
||||
assert: function(inputData) {
|
||||
assert.equal(inputData.name, "test")
|
||||
assert.equal(inputData.nestedTest.test, "test")
|
||||
assert.equal(inputData.testArray.length, 1)
|
||||
},
|
||||
returnData: [{testString: "test", testNumber: 15, nestedTest: {test: "test"}, testArray: [new Buffer("gakgakgak2", "utf-8"), 1]}]
|
||||
},testUnicode: {
|
||||
assert: function(inputData) {
|
||||
assert.equal(inputData, "🚀")
|
||||
},
|
||||
returnData: ["🚄"]
|
||||
},testMultipleItems: {
|
||||
assert: function(array, object, number, string, bool) {
|
||||
assert.equal(array.length, 2)
|
||||
assert.equal(array[0], "test1")
|
||||
assert.equal(array[1], "test2")
|
||||
assert.equal(number, 15)
|
||||
assert.equal(string, "marco")
|
||||
assert.equal(bool, false)
|
||||
},
|
||||
returnData: [[1, 2], {test: "bob"}, 25, "polo", false]
|
||||
},testMultipleItemsWithBuffer: {
|
||||
assert: function(array, object, number, string, binary) {
|
||||
assert.equal(array.length, 2)
|
||||
assert.equal(array[0], "test1")
|
||||
assert.equal(array[1], "test2")
|
||||
assert.equal(number, 15)
|
||||
assert.equal(string, "marco")
|
||||
assert.equal(binary.toString(), "gakgakgak2")
|
||||
},
|
||||
returnData: [[1, 2], {test: "bob"}, 25, "polo", new Buffer("gakgakgak2")]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
function socketCallback(testKey, socket, testCase) {
|
||||
return function() {
|
||||
testCase.assert.apply(undefined , arguments)
|
||||
var emitArguments = testCase.returnData;
|
||||
var ack = arguments[arguments.length - 1]
|
||||
ack.apply(socket, emitArguments)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports.socketCallback = socketCallback
|
||||
@@ -0,0 +1,20 @@
|
||||
function socketCallback(testKey, socket, testCase) {
|
||||
return function() {
|
||||
testCase.assert.apply(undefined , arguments)
|
||||
|
||||
var emitArguments = addArrays([testKey + "EmitReturn"], testCase.returnData)
|
||||
socket.emit.apply(socket, emitArguments)
|
||||
}
|
||||
}
|
||||
|
||||
function addArrays(firstArray, secondArray) {
|
||||
var length = secondArray.length
|
||||
var i;
|
||||
for(i = 0; i < length; i++) {
|
||||
firstArray.push(secondArray[i])
|
||||
}
|
||||
|
||||
return firstArray;
|
||||
}
|
||||
|
||||
module.exports.socketCallback = socketCallback
|
||||
@@ -0,0 +1,15 @@
|
||||
var app = require('http').createServer()
|
||||
var io = require('socket.io')(app);
|
||||
app.listen(6979)
|
||||
|
||||
|
||||
var acknowledgementsEvents = require("./acknowledgementEvents.js")
|
||||
var emitEvents = require("./emitEvents.js")
|
||||
var socketEventRegister = require("./socketEventRegister.js")
|
||||
|
||||
socketEventRegister.register(io, emitEvents.socketCallback, "Emit")
|
||||
socketEventRegister.register(io, acknowledgementsEvents.socketCallback, "Acknowledgement")
|
||||
|
||||
var nsp = io.of("/swift")
|
||||
socketEventRegister.register(nsp, emitEvents.socketCallback, "Emit")
|
||||
socketEventRegister.register(nsp, acknowledgementsEvents.socketCallback, "Acknowledgement")
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "socket.io-client-swift-test-server",
|
||||
"version": "0.0.1",
|
||||
"description": "A simple server to test aginst",
|
||||
"main": "main.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"author": "Lukas Schmidt",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"socket.io": "^1.3.6"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
var testCases = require("./TestCases.js")
|
||||
|
||||
function registerSocketForEvents(ioSocket, socketCallback, testKind) {
|
||||
ioSocket.on('connection', function(socket) {
|
||||
var testCase;
|
||||
for(testKey in testCases) {
|
||||
testCase = testCases[testKey]
|
||||
socket.on((testKey + testKind), socketCallback(testKey, socket, testCase))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
module.exports.register = registerSocketForEvents
|
||||
@@ -0,0 +1,26 @@
|
||||
<?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>io.socket.$(PRODUCT_NAME:rfc1034identifier)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string></string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,19 @@
|
||||
//
|
||||
// SocketIO-Mac.h
|
||||
// SocketIO-Mac
|
||||
//
|
||||
// Created by Nacho Soto on 7/11/15.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
//! Project version number for SocketIO-Mac.
|
||||
FOUNDATION_EXPORT double SocketIO_MacVersionNumber;
|
||||
|
||||
//! Project version string for SocketIO-Mac.
|
||||
FOUNDATION_EXPORT const unsigned char SocketIO_MacVersionString[];
|
||||
|
||||
// In this header, you should import all the public headers of your framework using statements like #import <SocketIO_Mac/PublicHeader.h>
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<?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>io.socket.$(PRODUCT_NAME:rfc1034identifier)</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>
|
||||
@@ -0,0 +1,139 @@
|
||||
//
|
||||
// SocketBasicPacketTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/7/15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class SocketBasicPacketTest: XCTestCase {
|
||||
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
|
||||
func testEmpyEmit() {
|
||||
let expectedSendString = "2[\"test\"]"
|
||||
let sendData = ["test"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testNullEmit() {
|
||||
let expectedSendString = "2[\"test\",null]"
|
||||
let sendData = ["test", NSNull()]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testStringEmit() {
|
||||
let expectedSendString = "2[\"test\",\"foo bar\"]"
|
||||
let sendData = ["test", "foo bar"]
|
||||
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()]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testArrayEmit() {
|
||||
let expectedSendString = "2[\"test\",[\"hello\",1,{\"test\":\"test\"}]]"
|
||||
let sendData = ["test", ["hello", 1, ["test": "test"]]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testBinaryEmit() {
|
||||
let expectedSendString = "51-[\"test\",{\"num\":0,\"_placeholder\":true}]"
|
||||
let sendData = ["test", data]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data])
|
||||
}
|
||||
|
||||
func testMultipleBinaryEmit() {
|
||||
let expectedSendString = "52-[\"test\",{\"data1\":{\"num\":0,\"_placeholder\":true},\"data2\":{\"num\":1,\"_placeholder\":true}}]"
|
||||
let sendData = ["test", ["data1": data, "data2": data2]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data, data2])
|
||||
}
|
||||
|
||||
func testEmitWithAck() {
|
||||
let expectedSendString = "20[\"test\"]"
|
||||
let sendData = ["test"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testEmitDataWithAck() {
|
||||
let expectedSendString = "51-0[\"test\",{\"num\":0,\"_placeholder\":true}]"
|
||||
let sendData = ["test", data]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data])
|
||||
}
|
||||
|
||||
// Acks
|
||||
func testEmptyAck() {
|
||||
let expectedSendString = "30[]"
|
||||
let packet = SocketPacket.packetFromEmit([], id: 0, nsp: "/", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testNullAck() {
|
||||
let expectedSendString = "30[null]"
|
||||
let sendData = [NSNull()]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testStringAck() {
|
||||
let expectedSendString = "30[\"test\"]"
|
||||
let sendData = ["test"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testJSONAck() {
|
||||
let expectedSendString = "30[{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
|
||||
let sendData = [["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testBinaryAck() {
|
||||
let expectedSendString = "61-0[{\"num\":0,\"_placeholder\":true}]"
|
||||
let sendData = [data]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data])
|
||||
}
|
||||
|
||||
func testMultipleBinaryAck() {
|
||||
let expectedSendString = "62-0[{\"data2\":{\"num\":0,\"_placeholder\":true},\"data1\":{\"num\":1,\"_placeholder\":true}}]"
|
||||
let sendData = [["data1": data, "data2": data2]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data2, data])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//
|
||||
// SocketEngineTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/15/15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class SocketEngineTest: XCTestCase {
|
||||
var client: SocketIOClient!
|
||||
var engine: SocketEngine!
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
client = SocketIOClient(socketURL: "")
|
||||
engine = SocketEngine(client: client, options: nil)
|
||||
|
||||
client.setTestable()
|
||||
}
|
||||
|
||||
func testBasicPollingMessage() {
|
||||
let expectation = expectationWithDescription("Basic polling test")
|
||||
client.on("blankTest") {data, ack in
|
||||
expectation.fulfill()
|
||||
}
|
||||
|
||||
engine.parsePollingMessage("15:42[\"blankTest\"]")
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testTwoPacketsInOnePollTest() {
|
||||
let finalExpectation = expectationWithDescription("Final packet in poll test")
|
||||
var gotBlank = false
|
||||
|
||||
client.on("blankTest") {data, ack in
|
||||
gotBlank = true
|
||||
}
|
||||
|
||||
client.on("stringTest") {data, ack in
|
||||
if let str = data[0] as? String where gotBlank {
|
||||
if str == "hello" {
|
||||
finalExpectation.fulfill()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
engine.parsePollingMessage("15:42[\"blankTest\"]24:42[\"stringTest\",\"hello\"]")
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//
|
||||
// SocketNamespacePacketTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/11/15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class SocketNamespacePacketTest: XCTestCase {
|
||||
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
|
||||
func testEmpyEmit() {
|
||||
let expectedSendString = "2/swift,[\"test\"]"
|
||||
let sendData = ["test"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testNullEmit() {
|
||||
let expectedSendString = "2/swift,[\"test\",null]"
|
||||
let sendData = ["test", NSNull()]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testStringEmit() {
|
||||
let expectedSendString = "2/swift,[\"test\",\"foo bar\"]"
|
||||
let sendData = ["test", "foo bar"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testJSONEmit() {
|
||||
let expectedSendString = "2/swift,[\"test\",{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
|
||||
let sendData = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testArrayEmit() {
|
||||
let expectedSendString = "2/swift,[\"test\",[\"hello\",1,{\"test\":\"test\"}]]"
|
||||
let sendData = ["test", ["hello", 1, ["test": "test"]]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testBinaryEmit() {
|
||||
let expectedSendString = "51-/swift,[\"test\",{\"num\":0,\"_placeholder\":true}]"
|
||||
let sendData = ["test", data]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data])
|
||||
}
|
||||
|
||||
func testMultipleBinaryEmit() {
|
||||
let expectedSendString = "52-/swift,[\"test\",{\"data1\":{\"num\":0,\"_placeholder\":true},\"data2\":{\"num\":1,\"_placeholder\":true}}]"
|
||||
let sendData = ["test", ["data1": data, "data2": data2]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data, data2])
|
||||
}
|
||||
|
||||
func testEmitWithAck() {
|
||||
let expectedSendString = "2/swift,0[\"test\"]"
|
||||
let sendData = ["test"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testEmitDataWithAck() {
|
||||
let expectedSendString = "51-/swift,0[\"test\",{\"num\":0,\"_placeholder\":true}]"
|
||||
let sendData = ["test", data]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data])
|
||||
}
|
||||
|
||||
// Acks
|
||||
func testEmptyAck() {
|
||||
let expectedSendString = "3/swift,0[]"
|
||||
let packet = SocketPacket.packetFromEmit([], id: 0, nsp: "/swift", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testNullAck() {
|
||||
let expectedSendString = "3/swift,0[null]"
|
||||
let sendData = [NSNull()]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testStringAck() {
|
||||
let expectedSendString = "3/swift,0[\"test\"]"
|
||||
let sendData = ["test"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testJSONAck() {
|
||||
let expectedSendString = "3/swift,0[{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
|
||||
let sendData = [["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testBinaryAck() {
|
||||
let expectedSendString = "61-/swift,0[{\"num\":0,\"_placeholder\":true}]"
|
||||
let sendData = [data]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data])
|
||||
}
|
||||
|
||||
func testMultipleBinaryAck() {
|
||||
let expectedSendString = "62-/swift,0[{\"data2\":{\"num\":0,\"_placeholder\":true},\"data1\":{\"num\":1,\"_placeholder\":true}}]"
|
||||
let sendData = [["data1": data, "data2": data2]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data2, data])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//
|
||||
// SocketSideEffectTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/11/15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class SocketSideEffectTest: XCTestCase {
|
||||
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
private var socket: SocketIOClient!
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
socket = SocketIOClient(socketURL: "")
|
||||
socket.setTestable()
|
||||
}
|
||||
|
||||
func testInitialCurrentAck() {
|
||||
XCTAssertEqual(socket.currentAck, -1)
|
||||
}
|
||||
|
||||
func testFirstAck() {
|
||||
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
|
||||
XCTAssertEqual(socket.currentAck, 0)
|
||||
}
|
||||
|
||||
func testSecondAck() {
|
||||
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
|
||||
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
|
||||
|
||||
XCTAssertEqual(socket.currentAck, 1)
|
||||
}
|
||||
|
||||
func testHandleAck() {
|
||||
let expectation = expectationWithDescription("handled ack")
|
||||
socket.emitWithAck("test")(timeoutAfter: 0) {data in
|
||||
XCTAssertEqual(data[0] as? String, "hello world")
|
||||
expectation.fulfill()
|
||||
}
|
||||
|
||||
socket.parseSocketMessage("30[\"hello world\"]")
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testHandleEvent() {
|
||||
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 testHandleBinaryEvent() {
|
||||
let expectation = expectationWithDescription("handled binary event")
|
||||
socket.on("test") {data, ack in
|
||||
if let dict = data[0] as? NSDictionary, data = dict["test"] as? NSData {
|
||||
XCTAssertEqual(data, self.data)
|
||||
expectation.fulfill()
|
||||
}
|
||||
}
|
||||
|
||||
socket.parseSocketMessage("51-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0}}]")
|
||||
socket.parseBinaryData(data)
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testHandleMultipleBinaryEvent() {
|
||||
let expectation = expectationWithDescription("handled multiple binary event")
|
||||
socket.on("test") {data, ack in
|
||||
if let dict = data[0] as? NSDictionary, data = dict["test"] as? NSData,
|
||||
data2 = dict["test2"] as? NSData {
|
||||
XCTAssertEqual(data, self.data)
|
||||
XCTAssertEqual(data2, self.data2)
|
||||
expectation.fulfill()
|
||||
}
|
||||
}
|
||||
|
||||
socket.parseSocketMessage("52-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0},\"test2\":{\"_placeholder\":true,\"num\":1}}]")
|
||||
socket.parseBinaryData(data)
|
||||
socket.parseBinaryData(data2)
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?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>io.socket.$(PRODUCT_NAME:rfc1034identifier)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string></string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,19 @@
|
||||
//
|
||||
// SocketIO-iOS.h
|
||||
// SocketIO-iOS
|
||||
//
|
||||
// Created by Nacho Soto on 7/11/15.
|
||||
//
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
//! Project version number for SocketIO-iOS.
|
||||
FOUNDATION_EXPORT double SocketIO_iOSVersionNumber;
|
||||
|
||||
//! Project version string for SocketIO-iOS.
|
||||
FOUNDATION_EXPORT const unsigned char SocketIO_iOSVersionString[];
|
||||
|
||||
// In this header, you should import all the public headers of your framework using statements like #import <SocketIO_iOS/PublicHeader.h>
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<?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>io.socket.$(PRODUCT_NAME:rfc1034identifier)</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>
|
||||
@@ -0,0 +1,25 @@
|
||||
//
|
||||
// SocketAckManagerTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Lukas Schmidt on 04.09.15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class SocketAckManagerTest: XCTestCase {
|
||||
var ackManager = SocketAckManager()
|
||||
|
||||
func testAddAcks() {
|
||||
let callbackExpection = self.expectationWithDescription("callbackExpection")
|
||||
let itemsArray = ["Hi", "ho"]
|
||||
func callback(items: [AnyObject]) {
|
||||
callbackExpection.fulfill()
|
||||
}
|
||||
ackManager.addAck(1, callback: callback)
|
||||
ackManager.executeAck(1, items: itemsArray)
|
||||
waitForExpectationsWithTimeout(3.0, handler: nil)
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
//
|
||||
// SocketParserTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Lukas Schmidt on 05.09.15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class SocketParserTest: XCTestCase {
|
||||
|
||||
//Format key: message; namespace-data-binary-id
|
||||
static let packetTypes: Dictionary<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),
|
||||
"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),
|
||||
"4/swift,": ("/swift", [], [], -1),
|
||||
"0/swift": ("/swift", [], [], -1),
|
||||
"1/swift": ("/swift", [], [], -1),
|
||||
"4\"ERROR\"": ("/", ["ERROR"], [], -1),
|
||||
"41": ("/", [1], [], -1)]
|
||||
|
||||
func testDisconnect() {
|
||||
let message = "1"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testConnect() {
|
||||
let message = "0"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testDisconnectNameSpace() {
|
||||
let message = "1/swift"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testConnecttNameSpace() {
|
||||
let message = "0/swift"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testIdEvent() {
|
||||
let message = "25[\"test\"]"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testBinaryPlaceholderAsString() {
|
||||
let message = "2[\"test\",\"~~0\"]"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testNameSpaceArrayParse() {
|
||||
let message = "2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testNameSpaceArrayAckParse() {
|
||||
let message = "3/swift,0[[\"test3\",\"test4\"]]"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testNameSpaceBinaryEventParse() {
|
||||
let message = "51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testNameSpaceBinaryAckParse() {
|
||||
let message = "61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testNamespaceErrorParse() {
|
||||
let message = "4/swift,"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testErrorTypeString() {
|
||||
let message = "4\"ERROR\""
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testErrorTypeInt() {
|
||||
let message = "41"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testInvalidInput() {
|
||||
let message = "8"
|
||||
switch SocketParser.parseString(message) {
|
||||
case .Left(_):
|
||||
return
|
||||
case .Right(_):
|
||||
XCTFail("Created packet when shouldn't have")
|
||||
}
|
||||
}
|
||||
|
||||
func testGenericParser() {
|
||||
var parser = SocketStringReader(message: "61-/swift,")
|
||||
XCTAssertEqual(parser.read(1), "6")
|
||||
XCTAssertEqual(parser.currentCharacter, "1")
|
||||
XCTAssertEqual(parser.readUntilStringOccurence("-"), "1")
|
||||
XCTAssertEqual(parser.currentCharacter, "/")
|
||||
}
|
||||
|
||||
func validateParseResult(message: String) {
|
||||
let validValues = SocketParserTest.packetTypes[message]!
|
||||
let packet = SocketParser.parseString(message)
|
||||
let type = message.substringWithRange(Range<String.Index>(start: message.startIndex, end: 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))
|
||||
XCTAssertEqual(packet.id, validValues.3)
|
||||
} else {
|
||||
XCTFail()
|
||||
}
|
||||
}
|
||||
|
||||
func testParsePerformance() {
|
||||
let keys = Array(SocketParserTest.packetTypes.keys)
|
||||
measureBlock({
|
||||
for item in keys.enumerate() {
|
||||
SocketParser.parseString(item.element)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//
|
||||
// SocketAckEmitter.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 9/16/15.
|
||||
//
|
||||
// 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
|
||||
|
||||
public final class SocketAckEmitter: NSObject {
|
||||
let socket: SocketIOClient
|
||||
let ackNum: Int
|
||||
|
||||
init(socket: SocketIOClient, ackNum: Int) {
|
||||
self.socket = socket
|
||||
self.ackNum = ackNum
|
||||
}
|
||||
|
||||
public func with(items: AnyObject...) {
|
||||
socket.emitAck(ackNum, withItems: items)
|
||||
}
|
||||
|
||||
public func with(items: [AnyObject]) {
|
||||
socket.emitAck(ackNum, withItems: items)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//
|
||||
// SocketAckManager.swift
|
||||
// SocketIO-Swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 4/3/15.
|
||||
//
|
||||
@@ -25,38 +25,38 @@
|
||||
import Foundation
|
||||
|
||||
private struct SocketAck: Hashable, Equatable {
|
||||
let ack:Int
|
||||
var callback:AckCallback!
|
||||
var hashValue:Int {
|
||||
let ack: Int
|
||||
var callback: AckCallback!
|
||||
var hashValue: Int {
|
||||
return ack.hashValue
|
||||
}
|
||||
|
||||
init(ack:Int) {
|
||||
init(ack: Int) {
|
||||
self.ack = ack
|
||||
}
|
||||
|
||||
init(ack:Int, callback:AckCallback) {
|
||||
init(ack: Int, callback: AckCallback) {
|
||||
self.ack = ack
|
||||
self.callback = callback
|
||||
}
|
||||
}
|
||||
|
||||
private func <(lhs:SocketAck, rhs:SocketAck) -> Bool {
|
||||
private func <(lhs: SocketAck, rhs: SocketAck) -> Bool {
|
||||
return lhs.ack < rhs.ack
|
||||
}
|
||||
|
||||
private func ==(lhs:SocketAck, rhs:SocketAck) -> Bool {
|
||||
private func ==(lhs: SocketAck, rhs: SocketAck) -> Bool {
|
||||
return lhs.ack == rhs.ack
|
||||
}
|
||||
|
||||
struct SocketAckManager {
|
||||
private var acks = Set<SocketAck>(minimumCapacity: 1)
|
||||
|
||||
mutating func addAck(ack:Int, callback:AckCallback) {
|
||||
mutating func addAck(ack: Int, callback: AckCallback) {
|
||||
acks.insert(SocketAck(ack: ack, callback: callback))
|
||||
}
|
||||
|
||||
mutating func executeAck(ack:Int, items:[AnyObject]?) {
|
||||
mutating func executeAck(ack: Int, items: [AnyObject]) {
|
||||
let callback = acks.remove(SocketAck(ack: ack))
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
@@ -64,7 +64,7 @@ struct SocketAckManager {
|
||||
}
|
||||
}
|
||||
|
||||
mutating func timeoutAck(ack:Int) {
|
||||
mutating func timeoutAck(ack: Int) {
|
||||
let callback = acks.remove(SocketAck(ack: ack))
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//
|
||||
// SocketAnyEvent.swift
|
||||
// Socket.IO-Swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/28/15.
|
||||
//
|
||||
@@ -24,11 +24,14 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
@objc public final class SocketAnyEvent {
|
||||
public let event:String!
|
||||
public let items:NSArray?
|
||||
@objc 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)"
|
||||
}
|
||||
|
||||
init(event:String, items:NSArray?) {
|
||||
init(event: String, items: NSArray?) {
|
||||
self.event = event
|
||||
self.items = items
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
//
|
||||
// SocketEngineClient.swift
|
||||
// Socket.IO-Swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/19/15.
|
||||
//
|
||||
@@ -26,12 +26,11 @@
|
||||
import Foundation
|
||||
|
||||
@objc public protocol SocketEngineClient {
|
||||
var handleQueue:dispatch_queue_attr_t! {get}
|
||||
var socketURL:String {get}
|
||||
var secure:Bool {get}
|
||||
var socketURL: String {get}
|
||||
var secure: Bool {get}
|
||||
|
||||
func didError(reason:AnyObject)
|
||||
func engineDidClose(reason:String)
|
||||
func parseSocketMessage(msg:String)
|
||||
func parseBinaryData(data:NSData)
|
||||
func didError(reason: AnyObject)
|
||||
func engineDidClose(reason: String)
|
||||
func parseSocketMessage(msg: String)
|
||||
func parseBinaryData(data: NSData)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//
|
||||
// SocketEnginePacketType.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/7/15.
|
||||
//
|
||||
// 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
|
||||
|
||||
@objc public enum SocketEnginePacketType: Int {
|
||||
case Open, Close, Ping, Pong, Message, Upgrade, Noop
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//
|
||||
// SocketEngineSpec.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/7/15.
|
||||
//
|
||||
// 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
|
||||
|
||||
@objc public protocol SocketEngineSpec {
|
||||
weak var client: SocketEngineClient? {get set}
|
||||
var cookies: [NSHTTPCookie]? {get}
|
||||
var sid: String {get}
|
||||
var socketPath: String {get}
|
||||
var urlPolling: String {get}
|
||||
var urlWebSocket: String {get}
|
||||
|
||||
init(client: SocketEngineClient, options: NSDictionary?)
|
||||
|
||||
func close()
|
||||
func open(opts: [String: AnyObject]?)
|
||||
func send(msg: String, withData datas: [NSData]?)
|
||||
func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData]?)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//
|
||||
// EventHandler.swift
|
||||
// Socket.IO-Swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 1/18/15.
|
||||
//
|
||||
@@ -24,24 +24,23 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
private func emitAckCallback(socket:SocketIOClient, num:Int)
|
||||
(items:AnyObject...) -> Void {
|
||||
socket.emitAck(num, withData: items)
|
||||
private func emitAckCallback(socket: SocketIOClient, num: Int?) -> SocketAckEmitter? {
|
||||
return num != nil ? SocketAckEmitter(socket: socket, ackNum: num!) : nil
|
||||
}
|
||||
|
||||
final class SocketEventHandler {
|
||||
let event:String!
|
||||
let callback:NormalCallback?
|
||||
struct SocketEventHandler {
|
||||
let event: String
|
||||
let callback: NormalCallback
|
||||
let id: NSUUID
|
||||
|
||||
init(event:String, callback:NormalCallback) {
|
||||
init(event: String, id: NSUUID = NSUUID(), callback: NormalCallback) {
|
||||
self.event = event
|
||||
self.id = id
|
||||
self.callback = callback
|
||||
}
|
||||
|
||||
func executeCallback(_ items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
|
||||
withSocket socket:SocketIOClient? = nil) {
|
||||
dispatch_async(dispatch_get_main_queue()) {[weak self] in
|
||||
self?.callback?(items, ack != nil ? emitAckCallback(socket!, ack!) : nil)
|
||||
}
|
||||
func executeCallback(items: [AnyObject], withAck ack: Int? = nil, withAckType type: Int? = nil,
|
||||
withSocket socket: SocketIOClient) {
|
||||
self.callback(items, emitAckCallback(socket, num: ack))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//
|
||||
// SocketFixUTF8.swift
|
||||
// Socket.IO-Swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/16/15.
|
||||
//
|
||||
@@ -25,14 +25,16 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
func fixDoubleUTF8(inout name:String) {
|
||||
let utf8 = name.dataUsingEncoding(NSISOLatin1StringEncoding)!
|
||||
let latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding)!
|
||||
name = latin1 as String
|
||||
func fixDoubleUTF8(inout name: String) {
|
||||
if let utf8 = name.dataUsingEncoding(NSISOLatin1StringEncoding),
|
||||
latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding) {
|
||||
name = latin1 as String
|
||||
}
|
||||
}
|
||||
|
||||
func doubleEncodeUTF8(inout str:String) {
|
||||
let latin1 = str.dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
let utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding)!
|
||||
str = utf8 as String
|
||||
func doubleEncodeUTF8(inout str: String) {
|
||||
if let latin1 = str.dataUsingEncoding(NSUTF8StringEncoding),
|
||||
utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding) {
|
||||
str = utf8 as String
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//
|
||||
// SocketIOClient.swift
|
||||
// Socket.IO-Swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 11/23/14.
|
||||
//
|
||||
@@ -24,120 +24,102 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient {
|
||||
private var anyHandler:((SocketAnyEvent) -> Void)?
|
||||
private var _closed = false
|
||||
private var _connected = false
|
||||
private var _connecting = false
|
||||
public final class SocketIOClient: NSObject, SocketEngineClient {
|
||||
public let socketURL: String
|
||||
|
||||
public private(set) var engine: SocketEngineSpec?
|
||||
public private(set) var secure = false
|
||||
public private(set) var status = SocketIOClientStatus.NotConnected
|
||||
|
||||
public var nsp = "/"
|
||||
public var options: Set<SocketIOClientOption>?
|
||||
public var reconnects = true
|
||||
public var reconnectWait = 10
|
||||
public var sid: String? {
|
||||
return engine?.sid
|
||||
}
|
||||
|
||||
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let logType = "SocketIOClient"
|
||||
|
||||
private var anyHandler: ((SocketAnyEvent) -> Void)?
|
||||
private var currentReconnectAttempt = 0
|
||||
private var handlers = ContiguousArray<SocketEventHandler>()
|
||||
private var connectParams:[String: AnyObject]?
|
||||
private var _secure = false
|
||||
private var _sid:String?
|
||||
private var _reconnecting = false
|
||||
private var reconnectTimer:NSTimer?
|
||||
private var connectParams: [String: AnyObject]?
|
||||
private var reconnectTimer: NSTimer?
|
||||
private var ackHandlers = SocketAckManager()
|
||||
|
||||
let reconnectAttempts:Int!
|
||||
let logType = "SocketClient"
|
||||
var ackHandlers = SocketAckManager()
|
||||
var currentAck = -1
|
||||
var log = false
|
||||
var waitingData = ContiguousArray<SocketPacket>()
|
||||
var sessionDelegate:NSURLSessionDelegate?
|
||||
|
||||
public let socketURL:String
|
||||
public let handleAckQueue = dispatch_queue_create("handleAckQueue", DISPATCH_QUEUE_SERIAL)
|
||||
public let handleQueue = dispatch_queue_create("handleQueue", DISPATCH_QUEUE_SERIAL)
|
||||
public let emitQueue = dispatch_queue_create("emitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
public var closed:Bool {
|
||||
return _closed
|
||||
}
|
||||
public var connected:Bool {
|
||||
return _connected
|
||||
}
|
||||
public var connecting:Bool {
|
||||
return _connecting
|
||||
}
|
||||
public var engine:SocketEngine?
|
||||
public var nsp = "/"
|
||||
public var opts:[String: AnyObject]?
|
||||
public var reconnects = true
|
||||
public var reconnecting:Bool {
|
||||
return _reconnecting
|
||||
}
|
||||
public var reconnectWait = 10
|
||||
public var secure:Bool {
|
||||
return _secure
|
||||
}
|
||||
public var sid:String? {
|
||||
return _sid
|
||||
}
|
||||
private(set) var currentAck = -1
|
||||
private(set) var handleQueue = dispatch_get_main_queue()
|
||||
private(set) var reconnectAttempts = -1
|
||||
var waitingData = [SocketPacket]()
|
||||
|
||||
/**
|
||||
Create a new SocketIOClient. opts can be omitted
|
||||
Type safe way to create a new SocketIOClient. opts can be omitted
|
||||
*/
|
||||
public init(var socketURL:String, opts:[String: AnyObject]? = nil) {
|
||||
public init(var socketURL: String, options: Set<SocketIOClientOption>? = nil) {
|
||||
if socketURL["https://"].matches().count != 0 {
|
||||
self._secure = true
|
||||
self.secure = true
|
||||
}
|
||||
|
||||
socketURL = socketURL["http://"] ~= ""
|
||||
socketURL = socketURL["https://"] ~= ""
|
||||
|
||||
self.socketURL = socketURL
|
||||
self.opts = opts
|
||||
self.options = options
|
||||
|
||||
// Set options
|
||||
if let sessionDelegate = opts?["sessionDelegate"] as? NSURLSessionDelegate {
|
||||
self.sessionDelegate = sessionDelegate
|
||||
}
|
||||
|
||||
if let connectParams = opts?["connectParams"] as? [String: AnyObject] {
|
||||
self.connectParams = connectParams
|
||||
}
|
||||
|
||||
if let log = opts?["log"] as? Bool {
|
||||
self.log = log
|
||||
}
|
||||
|
||||
if var nsp = opts?["nsp"] as? String {
|
||||
if nsp != "/" && nsp.hasPrefix("/") {
|
||||
nsp.removeAtIndex(nsp.startIndex)
|
||||
for option in options ?? [] {
|
||||
switch option {
|
||||
case .ConnectParams(let params):
|
||||
connectParams = params
|
||||
case .Reconnects(let reconnects):
|
||||
self.reconnects = reconnects
|
||||
case .ReconnectAttempts(let attempts):
|
||||
reconnectAttempts = attempts
|
||||
case .ReconnectWait(let wait):
|
||||
reconnectWait = abs(wait)
|
||||
case .Nsp(let nsp):
|
||||
self.nsp = nsp
|
||||
case .Log(let log):
|
||||
Logger.log = log
|
||||
case .Logger(let logger):
|
||||
Logger = logger
|
||||
case .HandleQueue(let queue):
|
||||
handleQueue = queue
|
||||
default:
|
||||
continue
|
||||
}
|
||||
|
||||
self.nsp = nsp
|
||||
}
|
||||
|
||||
if let reconnects = opts?["reconnects"] as? Bool {
|
||||
self.reconnects = reconnects
|
||||
}
|
||||
|
||||
if let reconnectAttempts = opts?["reconnectAttempts"] as? Int {
|
||||
self.reconnectAttempts = reconnectAttempts
|
||||
} else {
|
||||
self.reconnectAttempts = -1
|
||||
}
|
||||
|
||||
if let reconnectWait = opts?["reconnectWait"] as? Int {
|
||||
self.reconnectWait = abs(reconnectWait)
|
||||
}
|
||||
|
||||
super.init()
|
||||
}
|
||||
|
||||
public convenience init(socketURL:String, options:[String: AnyObject]?) {
|
||||
self.init(socketURL: socketURL, opts: options)
|
||||
/**
|
||||
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, opts: SocketOptionsDictionary? = nil)`
|
||||
*/
|
||||
public convenience init(socketURL: String, options: NSDictionary?) {
|
||||
self.init(socketURL: socketURL,
|
||||
options: SocketIOClientOption.NSDictionaryToSocketOptionsSet(options ?? [:]))
|
||||
}
|
||||
|
||||
deinit {
|
||||
SocketLogger.log("Client is being deinit", client: self)
|
||||
engine?.close(fast: true)
|
||||
Logger.log("Client is being deinit", type: logType)
|
||||
engine?.close()
|
||||
}
|
||||
|
||||
private func addEngine() {
|
||||
SocketLogger.log("Adding engine", client: self)
|
||||
|
||||
engine = SocketEngine(client: self, opts: opts)
|
||||
private func addEngine() -> SocketEngine {
|
||||
Logger.log("Adding engine", type: logType)
|
||||
|
||||
let newEngine = SocketEngine(client: self, options: options ?? [])
|
||||
|
||||
engine = newEngine
|
||||
return newEngine
|
||||
}
|
||||
|
||||
private func clearReconnectTimer() {
|
||||
reconnectTimer?.invalidate()
|
||||
reconnectTimer = nil
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -145,15 +127,11 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
Will turn off automatic reconnects.
|
||||
Pass true to fast if you're closing from a background task
|
||||
*/
|
||||
public func close(#fast:Bool) {
|
||||
SocketLogger.log("Closing socket", client: self)
|
||||
public func close() {
|
||||
Logger.log("Closing socket", type: logType)
|
||||
|
||||
reconnects = false
|
||||
_connecting = false
|
||||
_connected = false
|
||||
_reconnecting = false
|
||||
engine?.close(fast: fast)
|
||||
engine = nil
|
||||
didDisconnect("Closed")
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -166,48 +144,52 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
/**
|
||||
Connect to the server. If we aren't connected after timeoutAfter, call handler
|
||||
*/
|
||||
public func connect(#timeoutAfter:Int, withTimeoutHandler handler:(() -> Void)?) {
|
||||
if closed {
|
||||
SocketLogger.log("Warning! This socket was previously closed. This might be dangerous!", client: self)
|
||||
_closed = false
|
||||
} else if connected {
|
||||
return
|
||||
}
|
||||
|
||||
addEngine()
|
||||
engine?.open(opts: connectParams)
|
||||
|
||||
if timeoutAfter == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
|
||||
|
||||
dispatch_after(time, dispatch_get_main_queue()) {[weak self] in
|
||||
if let this = self where !this.connected {
|
||||
this._closed = true
|
||||
this._connecting = false
|
||||
this.engine?.close(fast: true)
|
||||
|
||||
handler?()
|
||||
public func connect(timeoutAfter timeoutAfter: Int,
|
||||
withTimeoutHandler handler: (() -> Void)?) {
|
||||
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
|
||||
|
||||
guard status != .Connected else {
|
||||
return
|
||||
}
|
||||
|
||||
if status == .Closed {
|
||||
Logger.log("Warning! This socket was previously closed. This might be dangerous!",
|
||||
type: logType)
|
||||
}
|
||||
|
||||
status = SocketIOClientStatus.Connecting
|
||||
addEngine().open(connectParams)
|
||||
|
||||
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()
|
||||
|
||||
handler?()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func createOnAck(event:String, items:[AnyObject]) -> OnAckCallback {
|
||||
private func createOnAck(items: [AnyObject]) -> OnAckCallback {
|
||||
return {[weak self, ack = ++currentAck] timeout, callback in
|
||||
if let this = self {
|
||||
this.ackHandlers.addAck(ack, callback: callback)
|
||||
|
||||
dispatch_async(this.emitQueue) {[weak this] in
|
||||
this?._emit(event, items, ack: ack)
|
||||
dispatch_async(this.emitQueue) {
|
||||
this._emit(items, ack: ack)
|
||||
}
|
||||
|
||||
if timeout != 0 {
|
||||
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
|
||||
|
||||
dispatch_after(time, dispatch_get_main_queue()) {[weak this] in
|
||||
this?.ackHandlers.timeoutAck(ack)
|
||||
dispatch_after(time, dispatch_get_main_queue()) {
|
||||
this.ackHandlers.timeoutAck(ack)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -215,43 +197,34 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
}
|
||||
|
||||
func didConnect() {
|
||||
SocketLogger.log("Socket connected", client: self)
|
||||
|
||||
_closed = false
|
||||
_connected = true
|
||||
_connecting = false
|
||||
_reconnecting = false
|
||||
Logger.log("Socket connected", type: logType)
|
||||
status = .Connected
|
||||
currentReconnectAttempt = 0
|
||||
reconnectTimer?.invalidate()
|
||||
reconnectTimer = nil
|
||||
_sid = engine?.sid
|
||||
clearReconnectTimer()
|
||||
|
||||
// Don't handle as internal because something crazy could happen where
|
||||
// we disconnect before it's handled
|
||||
handleEvent("connect", data: nil, isInternalMessage: false)
|
||||
handleEvent("connect", data: [], isInternalMessage: false)
|
||||
}
|
||||
|
||||
func didDisconnect(reason:String) {
|
||||
if closed {
|
||||
func didDisconnect(reason: String) {
|
||||
guard status != .Closed else {
|
||||
return
|
||||
}
|
||||
|
||||
SocketLogger.log("Disconnected: %@", client: self, args: reason)
|
||||
Logger.log("Disconnected: %@", type: logType, args: reason)
|
||||
|
||||
_closed = true
|
||||
_connected = false
|
||||
status = .Closed
|
||||
reconnects = false
|
||||
_connecting = false
|
||||
_reconnecting = false
|
||||
|
||||
// Make sure the engine is actually dead.
|
||||
engine?.close(fast: true)
|
||||
engine?.close()
|
||||
handleEvent("disconnect", data: [reason], isInternalMessage: true)
|
||||
}
|
||||
|
||||
/// error
|
||||
public func didError(reason:AnyObject) {
|
||||
SocketLogger.err("%@", client: self, args: reason)
|
||||
public func didError(reason: AnyObject) {
|
||||
Logger.error("%@", type: logType, args: reason)
|
||||
|
||||
handleEvent("error", data: reason as? [AnyObject] ?? [reason],
|
||||
isInternalMessage: true)
|
||||
@@ -260,33 +233,27 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
/**
|
||||
Same as close
|
||||
*/
|
||||
public func disconnect(#fast:Bool) {
|
||||
close(fast: fast)
|
||||
public func disconnect() {
|
||||
close()
|
||||
}
|
||||
|
||||
/**
|
||||
Send a message to the server
|
||||
*/
|
||||
public func emit(event:String, _ items:AnyObject...) {
|
||||
if !connected {
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(emitQueue) {[weak self] in
|
||||
self?._emit(event, items)
|
||||
}
|
||||
public func emit(event: String, _ items: AnyObject...) {
|
||||
emit(event, withItems: items)
|
||||
}
|
||||
|
||||
/**
|
||||
Same as emit, but meant for Objective-C
|
||||
*/
|
||||
public func emit(event:String, withItems items:[AnyObject]) {
|
||||
if !connected {
|
||||
public func emit(event: String, withItems items: [AnyObject]) {
|
||||
guard status == .Connected else {
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(emitQueue) {[weak self] in
|
||||
self?._emit(event, items)
|
||||
|
||||
dispatch_async(emitQueue) {
|
||||
self._emit([event] + items)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,39 +261,28 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
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 {
|
||||
if !connected {
|
||||
return createOnAck(event, items: items)
|
||||
}
|
||||
|
||||
return createOnAck(event, items: items)
|
||||
public func emitWithAck(event: String, _ items: AnyObject...) -> OnAckCallback {
|
||||
return emitWithAck(event, withItems: items)
|
||||
}
|
||||
|
||||
/**
|
||||
Same as emitWithAck, but for Objective-C
|
||||
*/
|
||||
public func emitWithAck(event:String, withItems items:[AnyObject]) -> OnAckCallback {
|
||||
if !connected {
|
||||
return createOnAck(event, items: items)
|
||||
}
|
||||
|
||||
return createOnAck(event, items: items)
|
||||
public func emitWithAck(event: String, withItems items: [AnyObject]) -> OnAckCallback {
|
||||
return createOnAck([event] + items)
|
||||
}
|
||||
|
||||
private func _emit(event:String, _ args:[AnyObject], ack:Int? = nil) {
|
||||
if !connected {
|
||||
private func _emit(data: [AnyObject], ack: Int? = nil) {
|
||||
guard status == .Connected else {
|
||||
return
|
||||
}
|
||||
|
||||
let packet = SocketPacket(type: nil, data: args, nsp: nsp, id: ack)
|
||||
let str:String
|
||||
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
|
||||
let str = packet.packetString
|
||||
|
||||
SocketParser.parseForEmit(packet)
|
||||
str = packet.createMessageForEvent(event)
|
||||
Logger.log("Emitting: %@", type: logType, args: str)
|
||||
|
||||
SocketLogger.log("Emitting: %@", client: self, args: str)
|
||||
|
||||
if packet.type == SocketPacket.PacketType.BINARY_EVENT {
|
||||
if packet.type == .BinaryEvent {
|
||||
engine?.send(str, withData: packet.binary)
|
||||
} else {
|
||||
engine?.send(str, withData: nil)
|
||||
@@ -334,73 +290,71 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
}
|
||||
|
||||
// If the server wants to know that the client received data
|
||||
func emitAck(ack:Int, withData args:[AnyObject]) {
|
||||
dispatch_async(emitQueue) {[weak self] in
|
||||
if let this = self where this.connected {
|
||||
let packet = SocketPacket(type: nil, data: args, nsp: this.nsp, id: ack)
|
||||
let str:String
|
||||
func emitAck(ack: Int, withItems items: [AnyObject]) {
|
||||
dispatch_async(emitQueue) {
|
||||
if self.status == .Connected {
|
||||
let packet = SocketPacket.packetFromEmit(items, id: ack ?? -1, nsp: self.nsp, ack: true)
|
||||
let str = packet.packetString
|
||||
|
||||
SocketParser.parseForEmit(packet)
|
||||
str = packet.createAck()
|
||||
Logger.log("Emitting Ack: %@", type: self.logType, args: str)
|
||||
|
||||
SocketLogger.log("Emitting Ack: %@", client: this, args: str)
|
||||
|
||||
if packet.type == SocketPacket.PacketType.BINARY_ACK {
|
||||
this.engine?.send(str, withData: packet.binary)
|
||||
if packet.type == SocketPacket.PacketType.BinaryAck {
|
||||
self.engine?.send(str, withData: packet.binary)
|
||||
} else {
|
||||
this.engine?.send(str, withData: nil)
|
||||
self.engine?.send(str, withData: nil)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func engineDidClose(reason:String) {
|
||||
_connected = false
|
||||
_connecting = false
|
||||
public func engineDidClose(reason: String) {
|
||||
waitingData.removeAll()
|
||||
|
||||
if closed || !reconnects {
|
||||
if status == .Closed || !reconnects {
|
||||
didDisconnect(reason)
|
||||
} else if !reconnecting {
|
||||
} else if status != .Reconnecting {
|
||||
status = .Reconnecting
|
||||
handleEvent("reconnect", data: [reason], isInternalMessage: true)
|
||||
tryReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
// Called when the socket gets an ack for something it sent
|
||||
func handleAck(ack:Int, data:AnyObject?) {
|
||||
SocketLogger.log("Handling ack: %@ with data: %@", client: self,
|
||||
args: ack, data ?? "")
|
||||
func handleAck(ack: Int, data: AnyObject?) {
|
||||
guard status == .Connected else {return}
|
||||
|
||||
Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
|
||||
|
||||
ackHandlers.executeAck(ack,
|
||||
items: (data as? [AnyObject]?) ?? (data != nil ? [data!] : nil))
|
||||
items: (data as? [AnyObject]) ?? (data != nil ? [data!] : []))
|
||||
}
|
||||
|
||||
/**
|
||||
Causes an event to be handled. Only use if you know what you're doing.
|
||||
*/
|
||||
public func handleEvent(event:String, data:[AnyObject]?, isInternalMessage:Bool = false,
|
||||
wantsAck ack:Int? = nil) {
|
||||
// println("Should do event: \(event) with data: \(data)")
|
||||
if !connected && !isInternalMessage {
|
||||
public func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool,
|
||||
wantsAck ack: Int? = nil) {
|
||||
guard status == .Connected || isInternalMessage else {
|
||||
return
|
||||
}
|
||||
|
||||
SocketLogger.log("Handling event: %@ with data: %@", client: self,
|
||||
args: event, data ?? "")
|
||||
Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data ?? "")
|
||||
|
||||
if anyHandler != nil {
|
||||
dispatch_async(dispatch_get_main_queue()) {[weak self] in
|
||||
self?.anyHandler?(SocketAnyEvent(event: event, items: data))
|
||||
dispatch_async(handleQueue) {
|
||||
self.anyHandler?(SocketAnyEvent(event: event, items: data))
|
||||
}
|
||||
}
|
||||
|
||||
for handler in handlers {
|
||||
if handler.event == event {
|
||||
if ack != nil {
|
||||
handler.executeCallback(data, withAck: ack!, withSocket: self)
|
||||
} else {
|
||||
handler.executeCallback(data)
|
||||
for handler in handlers where handler.event == event {
|
||||
if let ack = ack {
|
||||
dispatch_async(handleQueue) {
|
||||
handler.executeCallback(data, withAck: ack, withSocket: self)
|
||||
}
|
||||
} else {
|
||||
dispatch_async(handleQueue) {
|
||||
handler.executeCallback(data, withAck: ack, withSocket: self)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -411,7 +365,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
*/
|
||||
public func leaveNamespace() {
|
||||
if nsp != "/" {
|
||||
engine?.send("1/\(nsp)", withData: nil)
|
||||
engine?.send("1\(nsp)", withData: nil)
|
||||
nsp = "/"
|
||||
}
|
||||
}
|
||||
@@ -420,36 +374,69 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
Joins nsp if it is not /
|
||||
*/
|
||||
public func joinNamespace() {
|
||||
SocketLogger.log("Joining namespace", client: self)
|
||||
Logger.log("Joining namespace", type: logType)
|
||||
|
||||
if nsp != "/" {
|
||||
engine?.send("0/\(nsp)", withData: nil)
|
||||
engine?.send("0\(nsp)", withData: nil)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Joins namespace /
|
||||
*/
|
||||
public func joinNamespace(namespace: String) {
|
||||
self.nsp = namespace
|
||||
joinNamespace()
|
||||
}
|
||||
|
||||
/**
|
||||
Removes handler(s)
|
||||
*/
|
||||
public func off(event:String) {
|
||||
SocketLogger.log("Removing handler for event: %@", client: self, args: event)
|
||||
public func off(event: String) {
|
||||
Logger.log("Removing handler for event: %@", type: logType, args: event)
|
||||
|
||||
handlers = handlers.filter {$0.event == event ? false : true}
|
||||
handlers = ContiguousArray(handlers.filter { $0.event != event })
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler for an event.
|
||||
*/
|
||||
public func on(event:String, callback:NormalCallback) {
|
||||
SocketLogger.log("Adding handler for event: %@", client: self, args: event)
|
||||
public func on(event: String, callback: NormalCallback) {
|
||||
Logger.log("Adding handler for event: %@", type: logType, args: event)
|
||||
|
||||
let handler = SocketEventHandler(event: event, callback: callback)
|
||||
handlers.append(handler)
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a single-use handler for an event.
|
||||
*/
|
||||
public func once(event: String, callback: NormalCallback) {
|
||||
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}
|
||||
this.handlers = ContiguousArray(this.handlers.filter {$0.id != id})
|
||||
callback(data, ack)
|
||||
}
|
||||
|
||||
handlers.append(handler)
|
||||
}
|
||||
|
||||
/**
|
||||
Removes all handlers.
|
||||
Can be used after disconnecting to break any potential remaining retain cycles.
|
||||
*/
|
||||
public func removeAllHandlers() {
|
||||
handlers.removeAll(keepCapacity: false)
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler that will be called on every event.
|
||||
*/
|
||||
public func onAny(handler:(SocketAnyEvent) -> Void) {
|
||||
public func onAny(handler: (SocketAnyEvent) -> Void) {
|
||||
anyHandler = handler
|
||||
}
|
||||
|
||||
@@ -460,51 +447,53 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
connect()
|
||||
}
|
||||
|
||||
public func parseSocketMessage(msg:String) {
|
||||
SocketParser.parseSocketMessage(msg, socket: self)
|
||||
public func parseSocketMessage(msg: String) {
|
||||
dispatch_async(handleQueue) {
|
||||
SocketParser.parseSocketMessage(msg, socket: self)
|
||||
}
|
||||
}
|
||||
|
||||
public func parseBinaryData(data:NSData) {
|
||||
SocketParser.parseBinaryData(data, socket: self)
|
||||
public func parseBinaryData(data: NSData) {
|
||||
dispatch_async(handleQueue) {
|
||||
SocketParser.parseBinaryData(data, socket: self)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Trieds to reconnect to the server.
|
||||
Tries to reconnect to the server.
|
||||
*/
|
||||
public func reconnect() {
|
||||
_connected = false
|
||||
_connecting = false
|
||||
_reconnecting = false
|
||||
|
||||
engine?.stopPolling()
|
||||
tryReconnect()
|
||||
}
|
||||
|
||||
// We lost connection and should attempt to reestablish
|
||||
@objc private func tryReconnect() {
|
||||
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts {
|
||||
didDisconnect("Reconnect Failed")
|
||||
return
|
||||
} else if connected {
|
||||
_connecting = false
|
||||
_reconnecting = false
|
||||
return
|
||||
}
|
||||
|
||||
private func tryReconnect() {
|
||||
if reconnectTimer == nil {
|
||||
SocketLogger.log("Starting reconnect", client: self)
|
||||
Logger.log("Starting reconnect", type: logType)
|
||||
|
||||
_reconnecting = true
|
||||
status = .Reconnecting
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {[weak self] in
|
||||
if let this = self {
|
||||
this.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(this.reconnectWait),
|
||||
target: this, selector: "tryReconnect", userInfo: nil, repeats: true)
|
||||
}
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
self.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self.reconnectWait),
|
||||
target: self, selector: "_tryReconnect", userInfo: nil, repeats: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func _tryReconnect() {
|
||||
if status == .Connected {
|
||||
clearReconnectTimer()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
SocketLogger.log("Trying to reconnect", client: self)
|
||||
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
|
||||
clearReconnectTimer()
|
||||
didDisconnect("Reconnect Failed")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
Logger.log("Trying to reconnect", type: logType)
|
||||
handleEvent("reconnectAttempt", data: [reconnectAttempts - currentReconnectAttempt],
|
||||
isInternalMessage: true)
|
||||
|
||||
@@ -512,3 +501,18 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
connect()
|
||||
}
|
||||
}
|
||||
|
||||
// Test extensions
|
||||
extension SocketIOClient {
|
||||
func setTestable() {
|
||||
status = .Connected
|
||||
}
|
||||
|
||||
func setTestEngine(engine: SocketEngineSpec?) {
|
||||
self.engine = engine
|
||||
}
|
||||
|
||||
func emitTest(event: String, _ data: AnyObject...) {
|
||||
self._emit([event] + data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
//
|
||||
// SocketIOClientOption .swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/17/15.
|
||||
//
|
||||
// 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
|
||||
|
||||
public enum SocketIOClientOption: CustomStringConvertible, Hashable {
|
||||
case ConnectParams([String: AnyObject])
|
||||
case Reconnects(Bool)
|
||||
case ReconnectAttempts(Int)
|
||||
case ReconnectWait(Int)
|
||||
case ForcePolling(Bool)
|
||||
case ForceWebsockets(Bool)
|
||||
case Nsp(String)
|
||||
case Cookies([NSHTTPCookie])
|
||||
case Log(Bool)
|
||||
case Logger(SocketLogger)
|
||||
case SessionDelegate(NSURLSessionDelegate)
|
||||
case Path(String)
|
||||
case ExtraHeaders([String: String])
|
||||
case HandleQueue(dispatch_queue_t)
|
||||
|
||||
public var description: String {
|
||||
if let label = Mirror(reflecting: self).children.first?.label {
|
||||
return String(label[label.startIndex]).lowercaseString + String(label.characters.dropFirst())
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
public var hashValue: Int {
|
||||
return description.hashValue
|
||||
}
|
||||
|
||||
static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
|
||||
switch key {
|
||||
case "connectParams" where value is [String: AnyObject]:
|
||||
return .ConnectParams(value as! [String: AnyObject])
|
||||
case "reconnects" where value is Bool:
|
||||
return .Reconnects(value as! Bool)
|
||||
case "reconnectAttempts" where value is Int:
|
||||
return .ReconnectAttempts(value as! Int)
|
||||
case "reconnectWait" where value is Int:
|
||||
return .ReconnectWait(value as! Int)
|
||||
case "forcePolling" where value is Bool:
|
||||
return .ForcePolling(value as! Bool)
|
||||
case "forceWebsockets" where value is Bool:
|
||||
return .ForceWebsockets(value as! Bool)
|
||||
case "nsp" where value is String:
|
||||
return .Nsp(value as! String)
|
||||
case "cookies" where value is [NSHTTPCookie]:
|
||||
return .Cookies(value as! [NSHTTPCookie])
|
||||
case "log" where value is Bool:
|
||||
return .Log(value as! Bool)
|
||||
case "logger" where value is SocketLogger:
|
||||
return .Logger(value as! SocketLogger)
|
||||
case "sessionDelegate" where value is NSURLSessionDelegate:
|
||||
return .SessionDelegate(value as! NSURLSessionDelegate)
|
||||
case "path" where value is String:
|
||||
return .Path(value as! String)
|
||||
case "extraHeaders" where value is [String: String]:
|
||||
return .ExtraHeaders(value as! [String: String])
|
||||
case "handleQueue" where value is dispatch_queue_t:
|
||||
return .HandleQueue(value as! dispatch_queue_t)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func getSocketIOOptionValue() -> AnyObject? {
|
||||
return Mirror(reflecting: self).children.first?.value as? AnyObject
|
||||
}
|
||||
|
||||
static func NSDictionaryToSocketOptionsSet(dict: NSDictionary) -> Set<SocketIOClientOption> {
|
||||
var options = Set<SocketIOClientOption>()
|
||||
|
||||
for (rawKey, value) in dict {
|
||||
if let key = rawKey as? String, opt = keyValueToSocketIOClientOption(key, value: value) {
|
||||
options.insert(opt)
|
||||
}
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
static func SocketOptionsSetToNSDictionary(set: Set<SocketIOClientOption>) -> NSDictionary {
|
||||
let options = NSMutableDictionary()
|
||||
|
||||
for option in set {
|
||||
options[option.description] = option.getSocketIOOptionValue()
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
}
|
||||
|
||||
public func ==(lhs: SocketIOClientOption, rhs: SocketIOClientOption) -> Bool {
|
||||
return lhs.description == rhs.description
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//
|
||||
// SocketIOClientStatus.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 8/14/15.
|
||||
//
|
||||
// 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
|
||||
|
||||
@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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//
|
||||
// SocketLogger.swift
|
||||
// SocketIO-Swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 4/11/15.
|
||||
//
|
||||
@@ -24,51 +24,38 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
private let MESSAGE_LENGTH_MAX = 10000
|
||||
var Logger: SocketLogger = DefaultSocketLogger()
|
||||
|
||||
protocol SocketLogClient {
|
||||
var log:Bool {get set}
|
||||
var logType:String {get}
|
||||
public protocol SocketLogger: class {
|
||||
/// Whether to log or not
|
||||
var log: Bool {get set}
|
||||
|
||||
/// Normal log messages
|
||||
func log(message: String, type: String, args: AnyObject...)
|
||||
|
||||
/// Error Messages
|
||||
func error(message: String, type: String, args: AnyObject...)
|
||||
}
|
||||
|
||||
final class SocketLogger {
|
||||
private static let printQueue = dispatch_queue_create("printQueue", DISPATCH_QUEUE_SERIAL)
|
||||
|
||||
private static func shorten(item:AnyObject) -> CVarArgType {
|
||||
var str = toString(item)
|
||||
|
||||
if count(str) > MESSAGE_LENGTH_MAX {
|
||||
let endIndex = advance(str.startIndex, MESSAGE_LENGTH_MAX)
|
||||
|
||||
str = str.substringToIndex(endIndex)
|
||||
}
|
||||
|
||||
return str
|
||||
public extension SocketLogger {
|
||||
func log(message: String, type: String, args: AnyObject...) {
|
||||
abstractLog("Log", message: message, type: type, args: args)
|
||||
}
|
||||
|
||||
static func log(message:String, client:SocketLogClient, altType:String? = nil, args:AnyObject...) {
|
||||
if !client.log {
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(printQueue) {[type = client.logType] in
|
||||
let newArgs = args.map(SocketLogger.shorten)
|
||||
let replaced = String(format: message, arguments: newArgs)
|
||||
|
||||
NSLog("%@: %@", altType ?? type, replaced)
|
||||
}
|
||||
func error(message: String, type: String, args: AnyObject...) {
|
||||
abstractLog("ERROR", message: message, type: type, args: args)
|
||||
}
|
||||
|
||||
static func err(message:String, client:SocketLogClient, altType:String? = nil, args:AnyObject...) {
|
||||
if !client.log {
|
||||
return
|
||||
}
|
||||
private func abstractLog(logType: String, message: String, type: String, args: [AnyObject]) {
|
||||
guard log else { return }
|
||||
|
||||
dispatch_async(printQueue) {[type = client.logType] in
|
||||
let newArgs = args.map(SocketLogger.shorten)
|
||||
let replaced = String(format: message, arguments: newArgs)
|
||||
|
||||
NSLog("ERROR %@: %@", altType ?? type, replaced)
|
||||
}
|
||||
let newArgs = args.map {arg -> CVarArgType in String(arg)}
|
||||
let replaced = String(format: message, arguments: newArgs)
|
||||
|
||||
NSLog("%@ %@: %@", logType, type, replaced)
|
||||
}
|
||||
}
|
||||
|
||||
class DefaultSocketLogger: SocketLogger {
|
||||
var log = false
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//
|
||||
// SocketPacket.swift
|
||||
// Socket.IO-Swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 1/18/15.
|
||||
//
|
||||
@@ -21,62 +21,65 @@
|
||||
// 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
|
||||
|
||||
final class SocketPacket: Printable {
|
||||
var binary = ContiguousArray<NSData>()
|
||||
var currentPlace = 0
|
||||
var data:[AnyObject]?
|
||||
var description:String {
|
||||
var better = "SocketPacket {type: ~~0; data: ~~1; " +
|
||||
"id: ~~2; placeholders: ~~3;}"
|
||||
|
||||
better = better["~~0"] ~= (type != nil ? String(type!.rawValue) : "nil")
|
||||
better = better["~~1"] ~= (data != nil ? "\(data!)" : "nil")
|
||||
better = better["~~2"] ~= (id != nil ? String(id!) : "nil")
|
||||
better = better["~~3"] ~= (placeholders != nil ? String(placeholders!) : "nil")
|
||||
|
||||
return better
|
||||
}
|
||||
var id:Int?
|
||||
var justAck = false
|
||||
var nsp = ""
|
||||
var placeholders:Int?
|
||||
var type:PacketType?
|
||||
struct SocketPacket {
|
||||
private let placeholders: Int
|
||||
private var currentPlace = 0
|
||||
|
||||
private static let logType = "SocketPacket"
|
||||
|
||||
let nsp: String
|
||||
let id: Int
|
||||
let type: PacketType
|
||||
|
||||
enum PacketType:Int {
|
||||
case CONNECT = 0
|
||||
case DISCONNECT = 1
|
||||
case EVENT = 2
|
||||
case ACK = 3
|
||||
case ERROR = 4
|
||||
case BINARY_EVENT = 5
|
||||
case BINARY_ACK = 6
|
||||
enum PacketType: Int {
|
||||
case Connect, Disconnect, Event, Ack, Error, BinaryEvent, BinaryAck
|
||||
}
|
||||
|
||||
var args: [AnyObject]? {
|
||||
var arr = data
|
||||
|
||||
init?(str:String) {
|
||||
if let int = str.toInt(), raw = PacketType(rawValue: int) {
|
||||
self = raw
|
||||
if data.count == 0 {
|
||||
return nil
|
||||
} else {
|
||||
if type == PacketType.Event || type == PacketType.BinaryEvent {
|
||||
arr.removeAtIndex(0)
|
||||
return arr
|
||||
} else {
|
||||
return nil
|
||||
return arr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init(type:PacketType?, data:[AnyObject]? = nil, nsp:String = "",
|
||||
placeholders:Int? = nil, id:Int? = nil) {
|
||||
self.type = type
|
||||
self.data = data
|
||||
self.nsp = nsp
|
||||
self.placeholders = placeholders
|
||||
self.id = id
|
||||
var binary: [NSData]
|
||||
var data: [AnyObject]
|
||||
var description: String {
|
||||
return "SocketPacket {type: \(String(type.rawValue)); data: " +
|
||||
"\(String(data)); id: \(id); placeholders: \(placeholders); nsp: \(nsp)}"
|
||||
}
|
||||
|
||||
func getEvent() -> String {
|
||||
return data?.removeAtIndex(0) as! String
|
||||
var event: String {
|
||||
return data[0] as? String ?? String(data[0])
|
||||
}
|
||||
|
||||
func addData(data:NSData) -> Bool {
|
||||
var packetString: String {
|
||||
return createPacketString()
|
||||
}
|
||||
|
||||
init(type: SocketPacket.PacketType, data: [AnyObject] = [AnyObject](), id: Int = -1,
|
||||
nsp: String, placeholders: Int = 0, binary: [NSData] = [NSData]()) {
|
||||
self.data = data
|
||||
self.id = id
|
||||
self.nsp = nsp
|
||||
self.type = type
|
||||
self.placeholders = placeholders
|
||||
self.binary = binary
|
||||
}
|
||||
|
||||
mutating func addData(data: NSData) -> Bool {
|
||||
if placeholders == currentPlace {
|
||||
return true
|
||||
}
|
||||
@@ -92,86 +95,22 @@ final class SocketPacket: Printable {
|
||||
}
|
||||
}
|
||||
|
||||
func createMessageForEvent(event:String) -> String {
|
||||
let message:String
|
||||
|
||||
if binary.count == 0 {
|
||||
type = PacketType.EVENT
|
||||
|
||||
if nsp == "/" {
|
||||
if id == nil {
|
||||
message = "2[\"\(event)\""
|
||||
} else {
|
||||
message = "2\(id!)[\"\(event)\""
|
||||
}
|
||||
} else {
|
||||
if id == nil {
|
||||
message = "2/\(nsp),[\"\(event)\""
|
||||
} else {
|
||||
message = "2/\(nsp),\(id!)[\"\(event)\""
|
||||
}
|
||||
}
|
||||
} else {
|
||||
type = PacketType.BINARY_EVENT
|
||||
|
||||
if nsp == "/" {
|
||||
if id == nil {
|
||||
message = "5\(binary.count)-[\"\(event)\""
|
||||
} else {
|
||||
message = "5\(binary.count)-\(id!)[\"\(event)\""
|
||||
}
|
||||
} else {
|
||||
if id == nil {
|
||||
message = "5\(binary.count)-/\(nsp),[\"\(event)\""
|
||||
} else {
|
||||
message = "5\(binary.count)-/\(nsp),\(id!)[\"\(event)\""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return completeMessage(message)
|
||||
}
|
||||
|
||||
func createAck() -> String {
|
||||
var msg:String
|
||||
|
||||
if binary.count == 0 {
|
||||
type = PacketType.ACK
|
||||
|
||||
if nsp == "/" {
|
||||
msg = "3\(id!)["
|
||||
} else {
|
||||
msg = "3/\(nsp),\(id!)["
|
||||
}
|
||||
} else {
|
||||
type = PacketType.BINARY_ACK
|
||||
|
||||
if nsp == "/" {
|
||||
msg = "6\(binary.count)-\(id!)["
|
||||
} else {
|
||||
msg = "6\(binary.count)-/\(nsp),\(id!)["
|
||||
}
|
||||
}
|
||||
|
||||
return completeMessage(msg, ack: true)
|
||||
}
|
||||
|
||||
private func completeMessage(var message:String, ack:Bool = false) -> String {
|
||||
var err:NSError?
|
||||
|
||||
if data == nil || data!.count == 0 {
|
||||
private func completeMessage(var message: String, ack: Bool) -> String {
|
||||
if data.count == 0 {
|
||||
return message + "]"
|
||||
} else if !ack {
|
||||
message += ","
|
||||
}
|
||||
|
||||
for arg in data! {
|
||||
for arg in data {
|
||||
if arg is NSDictionary || arg is [AnyObject] {
|
||||
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
|
||||
options: NSJSONWritingOptions(0), error: &err)
|
||||
let jsonString = NSString(data: jsonSend!, encoding: NSUTF8StringEncoding)
|
||||
|
||||
message += jsonString! as String + ","
|
||||
do {
|
||||
let jsonSend = try NSJSONSerialization.dataWithJSONObject(arg,
|
||||
options: NSJSONWritingOptions(rawValue: 0))
|
||||
let jsonString = NSString(data: jsonSend, encoding: NSUTF8StringEncoding)
|
||||
|
||||
message += jsonString! as String + ","
|
||||
} catch {
|
||||
Logger.error("Error creating JSON object in SocketPacket.completeMessage", type: SocketPacket.logType)
|
||||
}
|
||||
} else if var str = arg as? String {
|
||||
str = str["\n"] ~= "\\\\n"
|
||||
str = str["\r"] ~= "\\\\r"
|
||||
@@ -191,29 +130,95 @@ final class SocketPacket: Printable {
|
||||
return message + "]"
|
||||
}
|
||||
|
||||
func fillInPlaceholders() {
|
||||
var newArr = NSMutableArray(array: data!)
|
||||
private func createAck() -> String {
|
||||
let msg: String
|
||||
|
||||
for i in 0..<data!.count {
|
||||
if let str = data?[i] as? String, num = str["~~(\\d)"].groups() {
|
||||
newArr[i] = binary[num[1].toInt()!]
|
||||
} else if data?[i] is NSDictionary || data?[i] is NSArray {
|
||||
newArr[i] = _fillInPlaceholders(data![i])
|
||||
if type == PacketType.Ack {
|
||||
if nsp == "/" {
|
||||
msg = "3\(id)["
|
||||
} else {
|
||||
msg = "3\(nsp),\(id)["
|
||||
}
|
||||
} else {
|
||||
if nsp == "/" {
|
||||
msg = "6\(binary.count)-\(id)["
|
||||
} else {
|
||||
msg = "6\(binary.count)-\(nsp),\(id)["
|
||||
}
|
||||
}
|
||||
|
||||
data = newArr as [AnyObject]
|
||||
return completeMessage(msg, ack: true)
|
||||
}
|
||||
|
||||
|
||||
private func createMessageForEvent() -> String {
|
||||
let message: String
|
||||
|
||||
if type == PacketType.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)
|
||||
}
|
||||
|
||||
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
|
||||
private func createPacketString() -> String {
|
||||
let str: String
|
||||
|
||||
if type == PacketType.Event || type == PacketType.BinaryEvent {
|
||||
str = createMessageForEvent()
|
||||
} else {
|
||||
str = createAck()
|
||||
}
|
||||
|
||||
return str
|
||||
}
|
||||
|
||||
mutating func fillInPlaceholders() {
|
||||
for i in 0..<data.count {
|
||||
if let str = data[i] as? String, num = str["~~(\\d)"].groups() {
|
||||
// Fill in binary placeholder with data
|
||||
data[i] = binary[Int(num[1])!]
|
||||
} else if data[i] is NSDictionary || data[i] is NSArray {
|
||||
data[i] = _fillInPlaceholders(data[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func _fillInPlaceholders(data: AnyObject) -> AnyObject {
|
||||
if let str = data as? String {
|
||||
if let num = str["~~(\\d)"].groups() {
|
||||
return binary[num[1].toInt()!]
|
||||
return binary[Int(num[1])!]
|
||||
} else {
|
||||
return str
|
||||
}
|
||||
} else if let dict = data as? NSDictionary {
|
||||
var newDict = NSMutableDictionary(dictionary: dict)
|
||||
let newDict = NSMutableDictionary(dictionary: dict)
|
||||
|
||||
for (key, value) in dict {
|
||||
newDict[key as! NSCopying] = _fillInPlaceholders(value)
|
||||
@@ -221,7 +226,7 @@ final class SocketPacket: Printable {
|
||||
|
||||
return newDict
|
||||
} else if let arr = data as? NSArray {
|
||||
var newArr = NSMutableArray(array: arr)
|
||||
let newArr = NSMutableArray(array: arr)
|
||||
|
||||
for i in 0..<arr.count {
|
||||
newArr[i] = _fillInPlaceholders(arr[i])
|
||||
@@ -233,3 +238,71 @@ final class SocketPacket: Printable {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SocketPacket {
|
||||
private static func findType(binCount: Int, ack: Bool) -> PacketType {
|
||||
switch binCount {
|
||||
case 0 where !ack:
|
||||
return PacketType.Event
|
||||
case 0 where ack:
|
||||
return PacketType.Ack
|
||||
case _ where !ack:
|
||||
return PacketType.BinaryEvent
|
||||
case _ where ack:
|
||||
return PacketType.BinaryAck
|
||||
default:
|
||||
return PacketType.Error
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
return packet
|
||||
}
|
||||
}
|
||||
|
||||
private extension SocketPacket {
|
||||
static func shred(data: AnyObject, inout binary: [NSData]) -> AnyObject {
|
||||
if let bin = data as? NSData {
|
||||
let placeholder = ["_placeholder" :true, "num": binary.count]
|
||||
|
||||
binary.append(bin)
|
||||
|
||||
return placeholder
|
||||
} else if var arr = data as? [AnyObject] {
|
||||
for i in 0..<arr.count {
|
||||
arr[i] = shred(arr[i], binary: &binary)
|
||||
}
|
||||
|
||||
return arr
|
||||
} else if let dict = data as? NSDictionary {
|
||||
let mutDict = NSMutableDictionary(dictionary: dict)
|
||||
|
||||
for (key, value) in dict {
|
||||
mutDict[key as! NSCopying] = shred(value, binary: &binary)
|
||||
}
|
||||
|
||||
return mutDict
|
||||
} else {
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
static func deconstructData(var data: [AnyObject]) -> ([AnyObject], [NSData]) {
|
||||
var binary = [NSData]()
|
||||
|
||||
for i in 0..<data.count {
|
||||
if data[i] is NSArray || data[i] is NSDictionary {
|
||||
data[i] = shred(data[i], binary: &binary)
|
||||
} else if let bin = data[i] as? NSData {
|
||||
data[i] = ["_placeholder" :true, "num": binary.count]
|
||||
binary.append(bin)
|
||||
}
|
||||
}
|
||||
|
||||
return (data, binary)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//
|
||||
// SocketParser.swift
|
||||
// Socket.IO-Swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
@@ -22,243 +22,157 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
class SocketParser {
|
||||
private static let shredder = SocketParser.PacketShredder()
|
||||
class SocketParser {
|
||||
|
||||
// Translation of socket.io-parser#deconstructPacket
|
||||
private final class PacketShredder {
|
||||
var buf = ContiguousArray<NSData>()
|
||||
|
||||
func shred(data:AnyObject) -> AnyObject {
|
||||
if let bin = data as? NSData {
|
||||
let placeholder = ["_placeholder" :true, "num": buf.count]
|
||||
|
||||
buf.append(bin)
|
||||
|
||||
return placeholder
|
||||
} else if let arr = data as? NSArray {
|
||||
var newArr = NSMutableArray(array: arr)
|
||||
|
||||
for i in 0..<arr.count {
|
||||
newArr[i] = shred(arr[i])
|
||||
}
|
||||
|
||||
return newArr
|
||||
} else if let dict = data as? NSDictionary {
|
||||
var newDict = NSMutableDictionary(dictionary: dict)
|
||||
|
||||
for (key, value) in newDict {
|
||||
newDict[key as! NSCopying] = shred(value)
|
||||
}
|
||||
|
||||
return newDict
|
||||
} else {
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
func deconstructPacket(packet:SocketPacket) {
|
||||
if packet.data == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var data = packet.data!
|
||||
|
||||
for i in 0..<data.count {
|
||||
if data[i] is NSArray || data[i] is NSDictionary {
|
||||
data[i] = shred(data[i])
|
||||
} else if let bin = data[i] as? NSData {
|
||||
data[i] = ["_placeholder" :true, "num": buf.count]
|
||||
buf.append(bin)
|
||||
}
|
||||
}
|
||||
|
||||
packet.data = data
|
||||
packet.binary = buf
|
||||
buf.removeAll(keepCapacity: true)
|
||||
private static func isCorrectNamespace(nsp: String, _ socket: SocketIOClient) -> Bool {
|
||||
return nsp == socket.nsp
|
||||
}
|
||||
|
||||
private static func handleConnect(p: SocketPacket, socket: SocketIOClient) {
|
||||
if p.nsp == "/" && socket.nsp != "/" {
|
||||
socket.joinNamespace()
|
||||
} else if p.nsp != "/" && socket.nsp == "/" {
|
||||
socket.didConnect()
|
||||
} else {
|
||||
socket.didConnect()
|
||||
}
|
||||
}
|
||||
|
||||
// Translation of socket.io-client#decodeString
|
||||
static func parseString(str:String) -> SocketPacket? {
|
||||
let arr = Array(str)
|
||||
let type = String(arr[0])
|
||||
private static func handlePacket(pack: SocketPacket, withSocket socket: SocketIOClient) {
|
||||
switch pack.type {
|
||||
case .Event where isCorrectNamespace(pack.nsp, socket):
|
||||
socket.handleEvent(pack.event, data: pack.args ?? [],
|
||||
isInternalMessage: false, wantsAck: pack.id)
|
||||
case .Ack where isCorrectNamespace(pack.nsp, socket):
|
||||
socket.handleAck(pack.id, data: pack.data)
|
||||
case .BinaryEvent where isCorrectNamespace(pack.nsp, socket):
|
||||
socket.waitingData.append(pack)
|
||||
case .BinaryAck where isCorrectNamespace(pack.nsp, socket):
|
||||
socket.waitingData.append(pack)
|
||||
case .Connect:
|
||||
handleConnect(pack, socket: socket)
|
||||
case .Disconnect:
|
||||
socket.didDisconnect("Got Disconnect")
|
||||
case .Error:
|
||||
socket.didError(pack.data)
|
||||
default:
|
||||
Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description)
|
||||
}
|
||||
}
|
||||
|
||||
static func parseString(message: String) -> Either<String, SocketPacket> {
|
||||
var parser = SocketStringReader(message: message)
|
||||
|
||||
if arr.count == 1 {
|
||||
return SocketPacket(type: SocketPacket.PacketType(str: type))
|
||||
guard let type = SocketPacket.PacketType(rawValue: Int(parser.read(1)) ?? -1) else {
|
||||
return .Left("Invalid packet type")
|
||||
}
|
||||
|
||||
var id = nil as Int?
|
||||
var nsp = ""
|
||||
var i = 0
|
||||
if !parser.hasNext {
|
||||
return .Right(SocketPacket(type: type, nsp: "/"))
|
||||
}
|
||||
|
||||
var namespace: String?
|
||||
var placeholders = -1
|
||||
|
||||
if type == "5" || type == "6" {
|
||||
var buf = ""
|
||||
|
||||
while arr[++i] != "-" {
|
||||
buf += String(arr[i])
|
||||
if i == arr.count {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if let holders = buf.toInt() where arr[i] == "-" {
|
||||
if type == .BinaryEvent || type == .BinaryAck {
|
||||
if let holders = Int(parser.readUntilStringOccurence("-")) {
|
||||
placeholders = holders
|
||||
} else {
|
||||
NSLog("Error parsing \(str)")
|
||||
return nil
|
||||
return .Left("Invalid packet")
|
||||
}
|
||||
}
|
||||
|
||||
if arr[i + 1] == "/" {
|
||||
while ++i < arr.count {
|
||||
let c = arr[i]
|
||||
|
||||
if c == "," {
|
||||
break
|
||||
}
|
||||
|
||||
nsp += String(c)
|
||||
if parser.currentCharacter == "/" {
|
||||
namespace = parser.readUntilStringOccurence(",") ?? parser.readUntilEnd()
|
||||
}
|
||||
|
||||
if !parser.hasNext {
|
||||
return .Right(SocketPacket(type: type, id: -1,
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
if i + 1 >= arr.count {
|
||||
return SocketPacket(type: SocketPacket.PacketType(str: type),
|
||||
nsp: nsp, placeholders: placeholders, id: id)
|
||||
}
|
||||
let d = message[parser.currentIndex.advancedBy(1)..<message.endIndex]
|
||||
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
|
||||
|
||||
let next = String(arr[i + 1])
|
||||
|
||||
if next.toInt() != nil {
|
||||
var c = ""
|
||||
while ++i < arr.count {
|
||||
if let int = String(arr[i]).toInt() {
|
||||
c += String(arr[i])
|
||||
} else {
|
||||
--i
|
||||
break
|
||||
}
|
||||
switch parseData(noPlaceholders) {
|
||||
case .Left(let err):
|
||||
// If first you don't succeed, try again
|
||||
if case let .Right(data) = parseData("\([noPlaceholders as AnyObject])") {
|
||||
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
|
||||
nsp: namespace ?? "/", placeholders: placeholders))
|
||||
} else {
|
||||
return .Left(err)
|
||||
}
|
||||
|
||||
id = c.toInt()
|
||||
case .Right(let data):
|
||||
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
|
||||
nsp: namespace ?? "/", placeholders: placeholders))
|
||||
}
|
||||
|
||||
if ++i < arr.count {
|
||||
let d = str[advance(str.startIndex, i)...advance(str.startIndex, count(str)-1)]
|
||||
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
|
||||
let data = SocketParser.parseData(noPlaceholders) as? [AnyObject] ?? [noPlaceholders]
|
||||
|
||||
return SocketPacket(type: SocketPacket.PacketType(str: type), data: data,
|
||||
nsp: nsp, placeholders: placeholders, id: id)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Parses data for events
|
||||
static func parseData(data:String) -> AnyObject? {
|
||||
var err:NSError?
|
||||
private static func parseData(data: String) -> Either<String, [AnyObject]> {
|
||||
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
||||
let parsed:AnyObject? = NSJSONSerialization.JSONObjectWithData(stringData!,
|
||||
options: NSJSONReadingOptions.MutableContainers, error: &err)
|
||||
|
||||
if err != nil {
|
||||
// println(err)
|
||||
return nil
|
||||
do {
|
||||
if let arr = try NSJSONSerialization.JSONObjectWithData(stringData!,
|
||||
options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] {
|
||||
return .Right(arr)
|
||||
} else {
|
||||
return .Left("Expected data array")
|
||||
}
|
||||
} catch {
|
||||
return .Left("Error parsing data for packet")
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
|
||||
static func parseForEmit(packet:SocketPacket) {
|
||||
shredder.deconstructPacket(packet)
|
||||
}
|
||||
|
||||
// Parses messages recieved
|
||||
static func parseSocketMessage(stringMessage:String, socket:SocketIOClient) {
|
||||
if stringMessage == "" {
|
||||
return
|
||||
}
|
||||
static func parseSocketMessage(message: String, socket: SocketIOClient) {
|
||||
guard !message.isEmpty else { return }
|
||||
|
||||
func checkNSP(nsp:String) -> Bool {
|
||||
return nsp == "" && socket.nsp != "/"
|
||||
}
|
||||
Logger.log("Parsing %@", type: "SocketParser", args: message)
|
||||
|
||||
SocketLogger.log("Parsing %@", client: socket, altType: "SocketParser", args: stringMessage)
|
||||
|
||||
let p:SocketPacket
|
||||
|
||||
if let pack = parseString(stringMessage) {
|
||||
p = pack
|
||||
} else {
|
||||
socket.didError("Error parsing packet")
|
||||
return
|
||||
}
|
||||
|
||||
SocketLogger.log("Decoded packet as: %@", client: socket, altType: "SocketParser", args: p)
|
||||
|
||||
if p.type == SocketPacket.PacketType.EVENT {
|
||||
if checkNSP(p.nsp) {
|
||||
return
|
||||
}
|
||||
|
||||
socket.handleEvent(p.getEvent(), data: p.data,
|
||||
isInternalMessage: false, wantsAck: p.id)
|
||||
} else if p.type == SocketPacket.PacketType.ACK {
|
||||
if checkNSP(p.nsp) {
|
||||
return
|
||||
}
|
||||
|
||||
socket.handleAck(p.id!, data: p.data)
|
||||
} else if p.type == SocketPacket.PacketType.BINARY_EVENT {
|
||||
if checkNSP(p.nsp) {
|
||||
return
|
||||
}
|
||||
|
||||
socket.waitingData.append(p)
|
||||
} else if p.type == SocketPacket.PacketType.BINARY_ACK {
|
||||
if checkNSP(p.nsp) {
|
||||
return
|
||||
}
|
||||
|
||||
p.justAck = true
|
||||
socket.waitingData.append(p)
|
||||
} else if p.type == SocketPacket.PacketType.CONNECT {
|
||||
if p.nsp == "" && socket.nsp != "/" {
|
||||
socket.joinNamespace()
|
||||
} else if p.nsp != "" && socket.nsp == "/" {
|
||||
socket.didConnect()
|
||||
} else {
|
||||
socket.didConnect()
|
||||
}
|
||||
} else if p.type == SocketPacket.PacketType.DISCONNECT {
|
||||
socket.didDisconnect("Got Disconnect")
|
||||
} else if p.type == SocketPacket.PacketType.ERROR {
|
||||
socket.didError(p.data == nil ? "Error" : p.data!)
|
||||
switch parseString(message) {
|
||||
case .Left(let err):
|
||||
Logger.error("\(err): %@", type: "SocketParser", args: message)
|
||||
case .Right(let pack):
|
||||
Logger.log("Decoded packet as: %@", type: "SocketParser", args: pack.description)
|
||||
handlePacket(pack, withSocket: socket)
|
||||
}
|
||||
}
|
||||
|
||||
static func parseBinaryData(data:NSData, socket:SocketIOClient) {
|
||||
if socket.waitingData.count == 0 {
|
||||
SocketLogger.err("Got data when not remaking packet", client: socket, altType: "SocketParser")
|
||||
static func parseBinaryData(data: NSData, socket: SocketIOClient) {
|
||||
guard !socket.waitingData.isEmpty else {
|
||||
Logger.error("Got data when not remaking packet", type: "SocketParser")
|
||||
return
|
||||
}
|
||||
|
||||
let shouldExecute = socket.waitingData[0].addData(data)
|
||||
|
||||
if !shouldExecute {
|
||||
// Should execute event?
|
||||
guard socket.waitingData[socket.waitingData.count - 1].addData(data) else {
|
||||
return
|
||||
}
|
||||
|
||||
let packet = socket.waitingData.removeAtIndex(0)
|
||||
var packet = socket.waitingData.removeLast()
|
||||
packet.fillInPlaceholders()
|
||||
|
||||
if !packet.justAck {
|
||||
socket.handleEvent(packet.getEvent(), data: packet.data,
|
||||
wantsAck: packet.id)
|
||||
if packet.type != .BinaryAck {
|
||||
socket.handleEvent(packet.event, data: packet.args ?? [],
|
||||
isInternalMessage: false, wantsAck: packet.id)
|
||||
} else {
|
||||
socket.handleAck(packet.id!, data: packet.data)
|
||||
socket.handleAck(packet.id, data: packet.args)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//
|
||||
// SocketStringReader.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Lukas Schmidt on 07.09.15.
|
||||
//
|
||||
// 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.
|
||||
|
||||
struct SocketStringReader {
|
||||
let message: String
|
||||
var currentIndex: String.Index
|
||||
var hasNext: Bool {
|
||||
return currentIndex != message.endIndex
|
||||
}
|
||||
|
||||
var currentCharacter: String {
|
||||
return String(message[currentIndex])
|
||||
}
|
||||
|
||||
init(message: String) {
|
||||
self.message = message
|
||||
currentIndex = message.startIndex
|
||||
}
|
||||
|
||||
mutating func advanceIndexBy(n: Int) {
|
||||
currentIndex = currentIndex.advancedBy(n)
|
||||
}
|
||||
|
||||
mutating func read(readLength: Int) -> String {
|
||||
let readString = message[currentIndex..<currentIndex.advancedBy(readLength)]
|
||||
advanceIndexBy(readLength)
|
||||
|
||||
return readString
|
||||
}
|
||||
|
||||
mutating func readUntilStringOccurence(string: String) -> String {
|
||||
let substring = message[currentIndex..<message.endIndex]
|
||||
guard let foundRange = substring.rangeOfString(string) else {
|
||||
currentIndex = message.endIndex
|
||||
|
||||
return substring
|
||||
}
|
||||
|
||||
advanceIndexBy(message.startIndex.distanceTo(foundRange.startIndex) + 1)
|
||||
|
||||
return substring.substringToIndex(foundRange.startIndex)
|
||||
}
|
||||
|
||||
mutating func readUntilEnd() -> String {
|
||||
return read(currentIndex.distanceTo(message.endIndex))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//
|
||||
// SocketTypes.swift
|
||||
// SocketIO-Swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 4/8/15.
|
||||
//
|
||||
@@ -24,11 +24,11 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
// @objc_block is undocumented, but is used because Swift assumes that all
|
||||
// Objective-C blocks are copied, but Objective-C assumes that Swift will copy it.
|
||||
// And the way things are done here, the bridging fails to copy the block in
|
||||
// SocketAckMap#addAck
|
||||
public typealias AckCallback = @objc_block (NSArray?) -> Void
|
||||
public typealias AckEmitter = (AnyObject...) -> Void
|
||||
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
|
||||
public typealias OnAckCallback = (timeout:UInt64, callback:AckCallback) -> Void
|
||||
public typealias AckCallback = ([AnyObject]) -> Void
|
||||
public typealias NormalCallback = ([AnyObject], SocketAckEmitter?) -> Void
|
||||
public typealias OnAckCallback = (timeoutAfter: UInt64, callback: AckCallback) -> Void
|
||||
|
||||
enum Either<E, V> {
|
||||
case Left(E)
|
||||
case Right(V)
|
||||
}
|
||||
@@ -13,23 +13,23 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
var swiftRegexCache = [String: NSRegularExpression]()
|
||||
private var swiftRegexCache = [String: NSRegularExpression]()
|
||||
|
||||
public class SwiftRegex: NSObject, BooleanType {
|
||||
internal class SwiftRegex: NSObject, BooleanType {
|
||||
var target:String
|
||||
var regex: NSRegularExpression
|
||||
|
||||
init(target:String, pattern:String, options:NSRegularExpressionOptions = nil) {
|
||||
|
||||
init(target:String, pattern:String, options:NSRegularExpressionOptions?) {
|
||||
self.target = target
|
||||
if let regex = swiftRegexCache[pattern] {
|
||||
self.regex = regex
|
||||
} else {
|
||||
var error: NSError?
|
||||
if let regex = NSRegularExpression(pattern: pattern, options:options, error:&error) {
|
||||
do {
|
||||
let regex = try NSRegularExpression(pattern: pattern, options:
|
||||
NSRegularExpressionOptions.DotMatchesLineSeparators)
|
||||
swiftRegexCache[pattern] = regex
|
||||
self.regex = regex
|
||||
}
|
||||
else {
|
||||
} catch let error as NSError {
|
||||
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
|
||||
self.regex = NSRegularExpression()
|
||||
}
|
||||
@@ -37,173 +37,167 @@ public class SwiftRegex: NSObject, BooleanType {
|
||||
super.init()
|
||||
}
|
||||
|
||||
class func failure(message: String) {
|
||||
println("SwiftRegex: "+message)
|
||||
//assert(false,"SwiftRegex: failed")
|
||||
private static func failure(message: String) {
|
||||
fatalError("SwiftRegex: \(message)")
|
||||
}
|
||||
|
||||
final var targetRange: NSRange {
|
||||
return NSRange(location: 0,length: count(target.utf16))
|
||||
private final var targetRange: NSRange {
|
||||
return NSRange(location: 0,length: target.utf16.count)
|
||||
}
|
||||
|
||||
final func substring(range: NSRange) -> String? {
|
||||
if ( range.location != NSNotFound ) {
|
||||
|
||||
private final func substring(range: NSRange) -> String? {
|
||||
if range.location != NSNotFound {
|
||||
return (target as NSString).substringWithRange(range)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
public func doesMatch(options: NSMatchingOptions = nil) -> Bool {
|
||||
return range(options: options).location != NSNotFound
|
||||
|
||||
func doesMatch(options: NSMatchingOptions!) -> Bool {
|
||||
return range(options).location != NSNotFound
|
||||
}
|
||||
|
||||
public func range(options: NSMatchingOptions = nil) -> NSRange {
|
||||
return regex.rangeOfFirstMatchInString(target as String, options: nil, range: targetRange)
|
||||
|
||||
func range(options: NSMatchingOptions) -> NSRange {
|
||||
return regex.rangeOfFirstMatchInString(target as String, options: [], range: targetRange)
|
||||
}
|
||||
|
||||
public func match(options: NSMatchingOptions = nil) -> String? {
|
||||
return substring(range(options: options))
|
||||
|
||||
func match(options: NSMatchingOptions) -> String? {
|
||||
return substring(range(options))
|
||||
}
|
||||
|
||||
public func groups(options: NSMatchingOptions = nil) -> [String]? {
|
||||
return groupsForMatch(regex.firstMatchInString(target as String, options: options, range: targetRange))
|
||||
|
||||
func groups() -> [String]? {
|
||||
return groupsForMatch(regex.firstMatchInString(target as String, options:
|
||||
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange))
|
||||
}
|
||||
|
||||
func groupsForMatch(match: NSTextCheckingResult!) -> [String]? {
|
||||
if match != 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
|
||||
} else {
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
public subscript(groupno: Int) -> String? {
|
||||
|
||||
subscript(groupno: Int) -> String? {
|
||||
get {
|
||||
return groups()?[groupno]
|
||||
}
|
||||
|
||||
|
||||
set(newValue) {
|
||||
if newValue == nil {
|
||||
return
|
||||
}
|
||||
|
||||
for match in matchResults()!.reverse() {
|
||||
|
||||
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(options: NSMatchingOptions = nil) -> [NSTextCheckingResult]? {
|
||||
let matches = regex.matchesInString(target as String, options: options, range: targetRange)
|
||||
as? [NSTextCheckingResult]
|
||||
|
||||
if matches != nil {
|
||||
return matches!
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
|
||||
func matchResults() -> [NSTextCheckingResult] {
|
||||
let matches = regex.matchesInString(target as String, options:
|
||||
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange)
|
||||
as [NSTextCheckingResult]
|
||||
|
||||
return matches
|
||||
}
|
||||
|
||||
public func ranges(options: NSMatchingOptions = nil) -> [NSRange] {
|
||||
return matchResults(options: options)!.map { $0.range }
|
||||
|
||||
func ranges() -> [NSRange] {
|
||||
return matchResults().map { $0.range }
|
||||
}
|
||||
|
||||
public func matches(options: NSMatchingOptions = nil) -> [String] {
|
||||
return matchResults(options: options)!.map( { self.substring($0.range)!})
|
||||
|
||||
func matches() -> [String] {
|
||||
return matchResults().map( { self.substring($0.range)!})
|
||||
}
|
||||
|
||||
public func allGroups(options: NSMatchingOptions = nil) -> [[String]?] {
|
||||
return matchResults(options: options)!.map {self.groupsForMatch($0)}
|
||||
|
||||
func allGroups() -> [[String]?] {
|
||||
return matchResults().map { self.groupsForMatch($0) }
|
||||
}
|
||||
|
||||
public func dictionary(options: NSMatchingOptions = nil) -> Dictionary<String,String> {
|
||||
|
||||
func dictionary(options: NSMatchingOptions!) -> Dictionary<String,String> {
|
||||
var out = Dictionary<String,String>()
|
||||
for match in matchResults(options: options)! {
|
||||
for match in matchResults() {
|
||||
out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))!
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String),
|
||||
options:NSMatchingOptions = nil) -> String {
|
||||
options:NSMatchingOptions) -> String {
|
||||
let out = NSMutableString()
|
||||
var pos = 0
|
||||
|
||||
regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {
|
||||
(match: NSTextCheckingResult!, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
|
||||
|
||||
let matchRange = match.range
|
||||
|
||||
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) )
|
||||
out.appendString( substitution(match!, stop) )
|
||||
pos = matchRange.location + matchRange.length
|
||||
}
|
||||
|
||||
|
||||
out.appendString(substring(NSRange(location:pos, length:targetRange.length-pos))!)
|
||||
|
||||
|
||||
return out as String
|
||||
}
|
||||
|
||||
public var boolValue: Bool {
|
||||
return doesMatch()
|
||||
|
||||
var boolValue: Bool {
|
||||
return doesMatch(nil)
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
public subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex {
|
||||
subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex {
|
||||
return SwiftRegex(target: self, pattern: pattern, options: options)
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
public subscript(pattern: String) -> SwiftRegex {
|
||||
return SwiftRegex(target: self, pattern: pattern)
|
||||
subscript(pattern: String) -> SwiftRegex {
|
||||
return SwiftRegex(target: self, pattern: pattern, options: nil)
|
||||
}
|
||||
}
|
||||
|
||||
public func ~= (left: SwiftRegex, right: String) -> String {
|
||||
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: nil)
|
||||
}, options: [])
|
||||
}
|
||||
|
||||
public func ~= (left: SwiftRegex, right: [String]) -> String {
|
||||
func ~= (left: SwiftRegex, right: [String]) -> String {
|
||||
var matchNumber = 0
|
||||
return left.substituteMatches({match, stop -> String in
|
||||
|
||||
|
||||
if ++matchNumber == right.count {
|
||||
stop.memory = true
|
||||
}
|
||||
|
||||
|
||||
return left.regex.replacementStringForResult( match,
|
||||
inString: left.target as String, offset: 0, template: right[matchNumber-1] )
|
||||
}, options: nil)
|
||||
}, options: [])
|
||||
}
|
||||
|
||||
public func ~= (left: SwiftRegex, right: (String) -> String) -> String {
|
||||
func ~= (left: SwiftRegex, right: (String) -> String) -> String {
|
||||
// return right(left.substring(match.range))
|
||||
return left.substituteMatches(
|
||||
{match, stop -> String in
|
||||
right(left.substring(match.range)!)
|
||||
}, options: nil)
|
||||
}, options: [])
|
||||
}
|
||||
|
||||
public func ~= (left: SwiftRegex, right: ([String]?) -> String) -> String {
|
||||
func ~= (left: SwiftRegex, right: ([String]?) -> String) -> String {
|
||||
return left.substituteMatches({match, stop -> String in
|
||||
return right(left.groupsForMatch(match))
|
||||
}, options: nil)
|
||||
}, options: [])
|
||||
}
|
||||
+443
-216
@@ -7,6 +7,8 @@
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
import Foundation
|
||||
import CoreFoundation
|
||||
import Security
|
||||
|
||||
public protocol WebSocketDelegate: class {
|
||||
func websocketDidConnect(socket: WebSocket)
|
||||
@@ -15,6 +17,10 @@ public protocol WebSocketDelegate: class {
|
||||
func websocketDidReceiveData(socket: WebSocket, data: NSData)
|
||||
}
|
||||
|
||||
public protocol WebSocketPongDelegate: class {
|
||||
func websocketDidReceivePong(socket: WebSocket)
|
||||
}
|
||||
|
||||
public class WebSocket : NSObject, NSStreamDelegate {
|
||||
|
||||
enum OpCode : UInt8 {
|
||||
@@ -62,7 +68,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let headerWSKeyName = "Sec-WebSocket-Key"
|
||||
let headerOriginName = "Origin"
|
||||
let headerWSAcceptName = "Sec-WebSocket-Accept"
|
||||
let BUFFER_MAX = 2048
|
||||
let BUFFER_MAX = 4096
|
||||
let FinMask: UInt8 = 0x80
|
||||
let OpCodeMask: UInt8 = 0x0F
|
||||
let RSVMask: UInt8 = 0x70
|
||||
@@ -78,70 +84,58 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
var buffer: NSMutableData?
|
||||
}
|
||||
|
||||
private var cookies:[NSHTTPCookie]?
|
||||
public weak var delegate: WebSocketDelegate?
|
||||
public weak var pongDelegate: WebSocketPongDelegate?
|
||||
public var onConnect: ((Void) -> Void)?
|
||||
public var onDisconnect: ((NSError?) -> Void)?
|
||||
public var onText: ((String) -> Void)?
|
||||
public var onData: ((NSData) -> Void)?
|
||||
public var onPong: ((Void) -> Void)?
|
||||
public var headers = Dictionary<String,String>()
|
||||
public var voipEnabled = false
|
||||
public var selfSignedSSL = false
|
||||
private var security: SSLSecurity?
|
||||
public var enabledSSLCipherSuites: [SSLCipherSuite]?
|
||||
public var isConnected :Bool {
|
||||
return connected
|
||||
}
|
||||
private var url: NSURL
|
||||
private var inputStream: NSInputStream?
|
||||
private var outputStream: NSOutputStream?
|
||||
private var isRunLoop = false
|
||||
private var connected = false
|
||||
private var writeQueue: NSOperationQueue?
|
||||
private var isCreated = false
|
||||
private var writeQueue = NSOperationQueue()
|
||||
private var readStack = Array<WSResponse>()
|
||||
private var inputQueue = Array<NSData>()
|
||||
private var fragBuffer: NSData?
|
||||
public var headers = Dictionary<String,String>()
|
||||
public var voipEnabled = false
|
||||
public var selfSignedSSL = false
|
||||
private var connectedBlock: ((Void) -> Void)? = nil
|
||||
private var disconnectedBlock: ((NSError?) -> Void)? = nil
|
||||
private var receivedTextBlock: ((String) -> Void)? = nil
|
||||
private var receivedDataBlock: ((NSData) -> Void)? = nil
|
||||
public var isConnected :Bool {
|
||||
return connected
|
||||
}
|
||||
private var certValidated = false
|
||||
private var didDisconnect = false
|
||||
|
||||
//init the websocket with a url
|
||||
public init(url: NSURL) {
|
||||
self.url = url
|
||||
}
|
||||
public convenience init(url: NSURL, cookies:[NSHTTPCookie]?) {
|
||||
self.init(url: url)
|
||||
self.cookies = cookies
|
||||
|
||||
writeQueue.maxConcurrentOperationCount = 1
|
||||
}
|
||||
//used for setting protocols.
|
||||
public convenience init(url: NSURL, protocols: Array<String>) {
|
||||
self.init(url: url)
|
||||
optionalProtocols = protocols
|
||||
}
|
||||
//closure based instead of the delegate
|
||||
public convenience init(url: NSURL, protocols: Array<String>, connect:((Void) -> Void), disconnect:((NSError?) -> Void), text:((String) -> Void), data:(NSData) -> Void) {
|
||||
self.init(url: url, protocols: protocols)
|
||||
connectedBlock = connect
|
||||
disconnectedBlock = disconnect
|
||||
receivedTextBlock = text
|
||||
receivedDataBlock = data
|
||||
}
|
||||
//same as above, just shorter
|
||||
public convenience init(url: NSURL, connect:((Void) -> Void), disconnect:((NSError?) -> Void), text:((String) -> Void)) {
|
||||
self.init(url: url)
|
||||
connectedBlock = connect
|
||||
disconnectedBlock = disconnect
|
||||
receivedTextBlock = text
|
||||
}
|
||||
//same as above, just shorter
|
||||
public convenience init(url: NSURL, connect:((Void) -> Void), disconnect:((NSError?) -> Void), data:((NSData) -> Void)) {
|
||||
self.init(url: url)
|
||||
connectedBlock = connect
|
||||
disconnectedBlock = disconnect
|
||||
receivedDataBlock = data
|
||||
}
|
||||
|
||||
///Connect to the websocket server on a background thread
|
||||
public func connect() {
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), {
|
||||
self.createHTTPRequest()
|
||||
})
|
||||
if isCreated {
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
///disconnect from the websocket server
|
||||
@@ -169,9 +163,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
//private method that starts the connection
|
||||
private func createHTTPRequest() {
|
||||
|
||||
let str: NSString = url.absoluteString!
|
||||
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
|
||||
url, kCFHTTPVersion1_1)
|
||||
url, kCFHTTPVersion1_1).takeRetainedValue()
|
||||
|
||||
var port = url.port
|
||||
if port == nil {
|
||||
@@ -181,35 +174,28 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
port = 80
|
||||
}
|
||||
}
|
||||
|
||||
if self.cookies != nil {
|
||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
|
||||
for (key, value) in headers {
|
||||
self.addHeader(urlRequest, key: key as! String, val: value as! String)
|
||||
}
|
||||
}
|
||||
|
||||
self.addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
|
||||
self.addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
|
||||
addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
|
||||
addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
|
||||
if let protocols = optionalProtocols {
|
||||
self.addHeader(urlRequest, key: headerWSProtocolName, val: ",".join(protocols))
|
||||
addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joinWithSeparator(","))
|
||||
}
|
||||
self.addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
|
||||
self.addHeader(urlRequest, key: headerWSKeyName, val: self.generateWebSocketKey())
|
||||
self.addHeader(urlRequest, key: headerOriginName, val: url.absoluteString!)
|
||||
self.addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
|
||||
addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
|
||||
addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey())
|
||||
addHeader(urlRequest, key: headerOriginName, val: url.absoluteString)
|
||||
addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
|
||||
for (key,value) in headers {
|
||||
self.addHeader(urlRequest, key: key, val: value)
|
||||
addHeader(urlRequest, key: key, val: value)
|
||||
}
|
||||
if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) {
|
||||
let serializedRequest = cfHTTPMessage.takeRetainedValue()
|
||||
initStreamsWithData(serializedRequest, Int(port!))
|
||||
}
|
||||
|
||||
let serializedRequest: NSData = CFHTTPMessageCopySerializedMessage(urlRequest.takeUnretainedValue()).takeUnretainedValue()
|
||||
self.initStreamsWithData(serializedRequest, Int(port!))
|
||||
}
|
||||
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
|
||||
private func addHeader(urlRequest: Unmanaged<CFHTTPMessage>,key: String, val: String) {
|
||||
private func addHeader(urlRequest: CFHTTPMessage,key: String, val: String) {
|
||||
let nsKey: NSString = key
|
||||
let nsVal: NSString = val
|
||||
CFHTTPMessageSetHeaderFieldValue(urlRequest.takeUnretainedValue(),
|
||||
CFHTTPMessageSetHeaderFieldValue(urlRequest,
|
||||
nsKey,
|
||||
nsVal)
|
||||
}
|
||||
@@ -221,8 +207,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
|
||||
key += "\(Character(uni))"
|
||||
}
|
||||
var data = key.dataUsingEncoding(NSUTF8StringEncoding)
|
||||
var baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0))
|
||||
let data = key.dataUsingEncoding(NSUTF8StringEncoding)
|
||||
let baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
|
||||
return baseKey!
|
||||
}
|
||||
//Start the stream connection and write the data to the output stream
|
||||
@@ -234,38 +220,70 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
var writeStream: Unmanaged<CFWriteStream>?
|
||||
let h: NSString = url.host!
|
||||
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
|
||||
inputStream = readStream!.takeUnretainedValue()
|
||||
outputStream = writeStream!.takeUnretainedValue()
|
||||
|
||||
inputStream!.delegate = self
|
||||
outputStream!.delegate = self
|
||||
inputStream = readStream!.takeRetainedValue()
|
||||
outputStream = writeStream!.takeRetainedValue()
|
||||
guard let inStream = inputStream, let outStream = outputStream else { return }
|
||||
inStream.delegate = self
|
||||
outStream.delegate = self
|
||||
if url.scheme == "wss" || url.scheme == "https" {
|
||||
inputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
|
||||
outputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
|
||||
inStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
|
||||
outStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
|
||||
} else {
|
||||
certValidated = true //not a https session, so no need to check SSL pinning
|
||||
}
|
||||
if self.voipEnabled {
|
||||
inputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
|
||||
outputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
|
||||
if voipEnabled {
|
||||
inStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
|
||||
outStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
|
||||
}
|
||||
if self.selfSignedSSL {
|
||||
if selfSignedSSL {
|
||||
let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
|
||||
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
isRunLoop = true
|
||||
inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
inputStream!.open()
|
||||
outputStream!.open()
|
||||
inStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
outStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
inStream.open()
|
||||
outStream.open()
|
||||
let bytes = UnsafePointer<UInt8>(data.bytes)
|
||||
outputStream!.write(bytes, maxLength: data.length)
|
||||
outStream.write(bytes, maxLength: data.length)
|
||||
while(isRunLoop) {
|
||||
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as! NSDate)
|
||||
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as NSDate)
|
||||
}
|
||||
}
|
||||
//delegate for the stream methods. Processes incoming bytes
|
||||
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
|
||||
|
||||
if let sec = security where !certValidated && (eventCode == .HasBytesAvailable || eventCode == .HasSpaceAvailable) {
|
||||
let possibleTrust: AnyObject? = aStream.propertyForKey(kCFStreamPropertySSLPeerTrust as String)
|
||||
if let trust: AnyObject = possibleTrust {
|
||||
let domain: AnyObject? = aStream.propertyForKey(kCFStreamSSLPeerName as String)
|
||||
if sec.isValid(trust as! SecTrustRef, domain: domain as! String?) {
|
||||
certValidated = true
|
||||
} else {
|
||||
let error = errorWithDetail("Invalid SSL certificate", code: 1)
|
||||
disconnectStream(error)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if eventCode == .HasBytesAvailable {
|
||||
if(aStream == inputStream) {
|
||||
processInputStream()
|
||||
@@ -278,42 +296,35 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
//disconnect the stream object
|
||||
private func disconnectStream(error: NSError?) {
|
||||
if writeQueue != nil {
|
||||
writeQueue!.waitUntilAllOperationsAreFinished()
|
||||
writeQueue.waitUntilAllOperationsAreFinished()
|
||||
if let stream = inputStream {
|
||||
stream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
stream.close()
|
||||
}
|
||||
if let stream = outputStream {
|
||||
stream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
stream.close()
|
||||
}
|
||||
inputStream!.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
outputStream!.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
inputStream!.close()
|
||||
outputStream!.close()
|
||||
inputStream = nil
|
||||
outputStream = nil
|
||||
isRunLoop = false
|
||||
certValidated = false
|
||||
doDisconnect(error)
|
||||
connected = false
|
||||
dispatch_async(queue,{
|
||||
if let disconnectBlock = self.disconnectedBlock {
|
||||
disconnectBlock(error)
|
||||
}
|
||||
self.delegate?.websocketDidDisconnect(self, error: error)
|
||||
})
|
||||
}
|
||||
|
||||
///handles the incoming bytes and sending them to the proper processing method
|
||||
private func processInputStream() {
|
||||
let buf = NSMutableData(capacity: BUFFER_MAX)
|
||||
var buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
|
||||
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
|
||||
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
|
||||
if length > 0 {
|
||||
if !connected {
|
||||
connected = processHTTP(buffer, bufferLen: length)
|
||||
if !connected {
|
||||
dispatch_async(queue,{
|
||||
//self.workaroundMethod()
|
||||
let error = self.errorWithDetail("Invalid HTTP upgrade", code: 1)
|
||||
if let disconnect = self.disconnectedBlock {
|
||||
disconnect(error)
|
||||
}
|
||||
self.delegate?.websocketDidDisconnect(self, error: error)
|
||||
})
|
||||
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
|
||||
@@ -332,8 +343,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if inputQueue.count > 0 {
|
||||
let data = inputQueue[0]
|
||||
var work = data
|
||||
if (fragBuffer != nil) {
|
||||
var combine = NSMutableData(data: fragBuffer!)
|
||||
if fragBuffer != nil {
|
||||
let combine = NSMutableData(data: fragBuffer!)
|
||||
combine.appendData(data)
|
||||
work = combine
|
||||
fragBuffer = nil
|
||||
@@ -362,13 +373,13 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
if totalSize > 0 {
|
||||
if validateResponse(buffer, bufferLen: totalSize) {
|
||||
dispatch_async(queue,{
|
||||
//self.workaroundMethod()
|
||||
if let connectBlock = self.connectedBlock {
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
guard let s = self else { return }
|
||||
if let connectBlock = s.onConnect {
|
||||
connectBlock()
|
||||
}
|
||||
self.delegate?.websocketDidConnect(self)
|
||||
})
|
||||
s.delegate?.websocketDidConnect(s)
|
||||
})
|
||||
totalSize += 1 //skip the last \n
|
||||
let restSize = bufferLen - totalSize
|
||||
if restSize > 0 {
|
||||
@@ -382,23 +393,24 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
|
||||
///validates the HTTP is a 101 as per the RFC spec
|
||||
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
|
||||
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, 0).takeRetainedValue()
|
||||
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
|
||||
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
|
||||
if CFHTTPMessageGetResponseStatusCode(response) != 101 {
|
||||
return false
|
||||
}
|
||||
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response)
|
||||
let headers: NSDictionary = cfHeaders.takeRetainedValue()
|
||||
let acceptKey = headers[headerWSAcceptName] as! NSString
|
||||
if acceptKey.length > 0 {
|
||||
return true
|
||||
if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {
|
||||
let headers = cfHeaders.takeRetainedValue() as NSDictionary
|
||||
let acceptKey = headers[headerWSAcceptName] as! NSString
|
||||
if acceptKey.length > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
///process the websocket data
|
||||
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
||||
var response = readStack.last
|
||||
let response = readStack.last
|
||||
if response != nil && bufferLen < 2 {
|
||||
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
||||
return
|
||||
@@ -414,7 +426,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
resp.bytesLeft -= len
|
||||
resp.buffer?.appendData(NSData(bytes: buffer, length: len))
|
||||
processResponse(resp)
|
||||
var offset = bufferLen - extra
|
||||
let offset = bufferLen - extra
|
||||
if extra > 0 {
|
||||
processExtra((buffer+offset), bufferLen: extra)
|
||||
}
|
||||
@@ -427,11 +439,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
var offset = 2
|
||||
if((isMasked > 0 || (RSVMask & buffer[0]) > 0) && receivedOpcode != OpCode.Pong.rawValue) {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
let error = self.errorWithDetail("masked and rsv data is not currently supported", code: errCode)
|
||||
if let disconnect = self.disconnectedBlock {
|
||||
disconnect(error)
|
||||
}
|
||||
self.delegate?.websocketDidDisconnect(self, error: error)
|
||||
doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
@@ -439,21 +447,13 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if !isControlFrame && (receivedOpcode != OpCode.BinaryFrame.rawValue && receivedOpcode != OpCode.ContinueFrame.rawValue &&
|
||||
receivedOpcode != OpCode.TextFrame.rawValue && receivedOpcode != OpCode.Pong.rawValue) {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
let error = self.errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode)
|
||||
if let disconnect = self.disconnectedBlock {
|
||||
disconnect(error)
|
||||
}
|
||||
self.delegate?.websocketDidDisconnect(self, error: error)
|
||||
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
if isControlFrame && isFin == 0 {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
let error = self.errorWithDetail("control frames can't be fragmented", code: errCode)
|
||||
if let disconnect = self.disconnectedBlock {
|
||||
disconnect(error)
|
||||
}
|
||||
self.delegate?.websocketDidDisconnect(self, error: error)
|
||||
doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
@@ -462,8 +462,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if payloadLen == 1 {
|
||||
code = CloseCode.ProtocolError.rawValue
|
||||
} else if payloadLen > 1 {
|
||||
var codeBuffer = UnsafePointer<UInt16>((buffer+offset))
|
||||
code = codeBuffer[0].byteSwapped
|
||||
let codeBuffer = UnsafePointer<UInt16>((buffer+offset))
|
||||
code = codeBuffer[0].bigEndian
|
||||
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
|
||||
code = CloseCode.ProtocolError.rawValue
|
||||
}
|
||||
@@ -473,17 +473,13 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let len = Int(payloadLen-2)
|
||||
if len > 0 {
|
||||
let bytes = UnsafePointer<UInt8>((buffer+offset))
|
||||
var str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
|
||||
let str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
|
||||
if str == nil {
|
||||
code = CloseCode.ProtocolError.rawValue
|
||||
}
|
||||
}
|
||||
}
|
||||
let error = self.errorWithDetail("connection closed by server", code: code)
|
||||
if let disconnect = self.disconnectedBlock {
|
||||
disconnect(error)
|
||||
}
|
||||
self.delegate?.websocketDidDisconnect(self, error: error)
|
||||
doDisconnect(errorWithDetail("connection closed by server", code: code))
|
||||
writeError(code)
|
||||
return
|
||||
}
|
||||
@@ -494,13 +490,17 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
var dataLength = UInt64(payloadLen)
|
||||
if dataLength == 127 {
|
||||
let bytes = UnsafePointer<UInt64>((buffer+offset))
|
||||
dataLength = bytes[0].byteSwapped
|
||||
dataLength = bytes[0].bigEndian
|
||||
offset += sizeof(UInt64)
|
||||
} else if dataLength == 126 {
|
||||
let bytes = UnsafePointer<UInt16>((buffer+offset))
|
||||
dataLength = UInt64(bytes[0].byteSwapped)
|
||||
dataLength = UInt64(bytes[0].bigEndian)
|
||||
offset += sizeof(UInt16)
|
||||
}
|
||||
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
|
||||
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
||||
return
|
||||
}
|
||||
var len = dataLength
|
||||
if dataLength > UInt64(bufferLen) {
|
||||
len = UInt64(bufferLen-offset)
|
||||
@@ -513,7 +513,15 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
|
||||
}
|
||||
if receivedOpcode == OpCode.Pong.rawValue {
|
||||
let step = offset + Int(len)
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
guard let s = self else { return }
|
||||
if let pongBlock = s.onPong {
|
||||
pongBlock()
|
||||
}
|
||||
s.pongDelegate?.websocketDidReceivePong(s)
|
||||
})
|
||||
|
||||
let step = Int(offset+numericCast(len))
|
||||
let extra = bufferLen-step
|
||||
if extra > 0 {
|
||||
processRawMessage((buffer+step), bufferLen: extra)
|
||||
@@ -526,11 +534,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
if isFin == 0 && receivedOpcode == OpCode.ContinueFrame.rawValue && response == nil {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
let error = self.errorWithDetail("continue frame before a binary or text frame", code: errCode)
|
||||
if let disconnect = self.disconnectedBlock {
|
||||
disconnect(error)
|
||||
}
|
||||
self.delegate?.websocketDidDisconnect(self, error: error)
|
||||
doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
@@ -538,12 +542,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if(response == nil) {
|
||||
if receivedOpcode == OpCode.ContinueFrame.rawValue {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
let error = self.errorWithDetail("first frame can't be a continue frame",
|
||||
code: errCode)
|
||||
if let disconnect = self.disconnectedBlock {
|
||||
disconnect(error)
|
||||
}
|
||||
self.delegate?.websocketDidDisconnect(self, error: error)
|
||||
doDisconnect(errorWithDetail("first frame can't be a continue frame",
|
||||
code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
@@ -557,12 +557,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
response!.bytesLeft = Int(dataLength)
|
||||
} else {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
let error = self.errorWithDetail("second and beyond of fragment message must be a continue frame",
|
||||
code: errCode)
|
||||
if let disconnect = self.disconnectedBlock {
|
||||
disconnect(error)
|
||||
}
|
||||
self.delegate?.websocketDidDisconnect(self, error: error)
|
||||
doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame",
|
||||
code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
@@ -578,7 +574,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
processResponse(response!)
|
||||
}
|
||||
|
||||
let step = offset + Int(len)
|
||||
let step = Int(offset+numericCast(len))
|
||||
let extra = bufferLen-step
|
||||
if(extra > 0) {
|
||||
processExtra((buffer+step), bufferLen: extra)
|
||||
@@ -603,26 +599,28 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let data = response.buffer! //local copy so it is perverse for writing
|
||||
dequeueWrite(data, code: OpCode.Pong)
|
||||
} else if response.code == .TextFrame {
|
||||
var str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
|
||||
let str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
|
||||
if str == nil {
|
||||
writeError(CloseCode.Encoding.rawValue)
|
||||
return false
|
||||
}
|
||||
dispatch_async(queue,{
|
||||
if let textBlock = self.receivedTextBlock{
|
||||
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
guard let s = self else { return }
|
||||
if let textBlock = s.onText {
|
||||
textBlock(str! as String)
|
||||
}
|
||||
self.delegate?.websocketDidReceiveMessage(self, text: 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,{
|
||||
//self.workaroundMethod()
|
||||
if let dataBlock = self.receivedDataBlock{
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
guard let s = self else { return }
|
||||
if let dataBlock = s.onData {
|
||||
dataBlock(data)
|
||||
}
|
||||
self.delegate?.websocketDidReceiveData(self, data: data)
|
||||
})
|
||||
s.delegate?.websocketDidReceiveData(s, data: data)
|
||||
})
|
||||
}
|
||||
readStack.removeLast()
|
||||
return true
|
||||
@@ -640,52 +638,39 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
///write a an error to the socket
|
||||
private func writeError(code: UInt16) {
|
||||
let buf = NSMutableData(capacity: sizeof(UInt16))
|
||||
var buffer = UnsafeMutablePointer<UInt16>(buf!.bytes)
|
||||
buffer[0] = code.byteSwapped
|
||||
let buffer = UnsafeMutablePointer<UInt16>(buf!.bytes)
|
||||
buffer[0] = code.bigEndian
|
||||
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
|
||||
}
|
||||
///used to write things to the stream in a
|
||||
///used to write things to the stream
|
||||
private func dequeueWrite(data: NSData, code: OpCode) {
|
||||
if writeQueue == nil {
|
||||
writeQueue = NSOperationQueue()
|
||||
writeQueue!.maxConcurrentOperationCount = 1
|
||||
if !isConnected {
|
||||
return
|
||||
}
|
||||
writeQueue!.addOperationWithBlock {
|
||||
writeQueue.addOperationWithBlock { [weak self] in
|
||||
//stream isn't ready, let's wait
|
||||
var tries = 0;
|
||||
while self.outputStream == nil || !self.connected {
|
||||
if(tries < 5) {
|
||||
sleep(1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
tries++;
|
||||
}
|
||||
if !self.connected {
|
||||
return
|
||||
}
|
||||
guard let s = self else { return }
|
||||
var offset = 2
|
||||
UINT16_MAX
|
||||
let bytes = UnsafeMutablePointer<UInt8>(data.bytes)
|
||||
let dataLength = data.length
|
||||
let frame = NSMutableData(capacity: dataLength + self.MaxFrameSize)
|
||||
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
|
||||
let buffer = UnsafeMutablePointer<UInt8>(frame!.mutableBytes)
|
||||
buffer[0] = self.FinMask | code.rawValue
|
||||
buffer[0] = s.FinMask | code.rawValue
|
||||
if dataLength < 126 {
|
||||
buffer[1] = CUnsignedChar(dataLength)
|
||||
} else if dataLength <= Int(UInt16.max) {
|
||||
buffer[1] = 126
|
||||
var sizeBuffer = UnsafeMutablePointer<UInt16>((buffer+offset))
|
||||
sizeBuffer[0] = UInt16(dataLength).byteSwapped
|
||||
let sizeBuffer = UnsafeMutablePointer<UInt16>((buffer+offset))
|
||||
sizeBuffer[0] = UInt16(dataLength).bigEndian
|
||||
offset += sizeof(UInt16)
|
||||
} else {
|
||||
buffer[1] = 127
|
||||
var sizeBuffer = UnsafeMutablePointer<UInt64>((buffer+offset))
|
||||
sizeBuffer[0] = UInt64(dataLength).byteSwapped
|
||||
let sizeBuffer = UnsafeMutablePointer<UInt64>((buffer+offset))
|
||||
sizeBuffer[0] = UInt64(dataLength).bigEndian
|
||||
offset += sizeof(UInt64)
|
||||
}
|
||||
buffer[1] |= self.MaskMask
|
||||
var maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
|
||||
buffer[1] |= s.MaskMask
|
||||
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
|
||||
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
|
||||
offset += sizeof(UInt32)
|
||||
|
||||
@@ -695,26 +680,24 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
var total = 0
|
||||
while true {
|
||||
if self.outputStream == nil {
|
||||
if !s.isConnected {
|
||||
break
|
||||
}
|
||||
guard let outStream = s.outputStream else { break }
|
||||
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
|
||||
var len = self.outputStream?.write(writeBuffer, maxLength: offset-total)
|
||||
if len == nil || len! < 0 {
|
||||
let len = outStream.write(writeBuffer, maxLength: offset-total)
|
||||
if len < 0 {
|
||||
var error: NSError?
|
||||
if let streamError = self.outputStream?.streamError {
|
||||
if let streamError = outStream.streamError {
|
||||
error = streamError
|
||||
} else {
|
||||
let errCode = InternalErrorCode.OutputStreamWriteError.rawValue
|
||||
error = self.errorWithDetail("output stream error during write", code: errCode)
|
||||
error = s.errorWithDetail("output stream error during write", code: errCode)
|
||||
}
|
||||
if let disconnect = self.disconnectedBlock {
|
||||
disconnect(error)
|
||||
}
|
||||
self.delegate?.websocketDidDisconnect(self, error: error)
|
||||
s.doDisconnect(error)
|
||||
break
|
||||
} else {
|
||||
total += len!
|
||||
total += len
|
||||
}
|
||||
if total >= offset {
|
||||
break
|
||||
@@ -724,4 +707,248 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
///used to preform the disconnect delegate
|
||||
private func doDisconnect(error: NSError?) {
|
||||
if !didDisconnect {
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.didDisconnect = true
|
||||
if let disconnect = s.onDisconnect {
|
||||
disconnect(error)
|
||||
}
|
||||
s.delegate?.websocketDidDisconnect(s, error: error)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private class SSLCert {
|
||||
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
|
||||
*/
|
||||
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
|
||||
*/
|
||||
init(key: SecKeyRef) {
|
||||
self.key = key
|
||||
}
|
||||
}
|
||||
|
||||
private class SSLSecurity {
|
||||
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
|
||||
*/
|
||||
convenience init(usePublicKeys: Bool = false) {
|
||||
let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".")
|
||||
var collect = Array<SSLCert>()
|
||||
for path in paths {
|
||||
if let d = NSData(contentsOfFile: path as String) {
|
||||
collect.append(SSLCert(data: d))
|
||||
}
|
||||
}
|
||||
self.init(certs:collect, 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
|
||||
*/
|
||||
init(certs: [SSLCert], usePublicKeys: Bool) {
|
||||
self.usePublicKeys = usePublicKeys
|
||||
|
||||
if self.usePublicKeys {
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), {
|
||||
var collect = Array<SecKeyRef>()
|
||||
for cert in certs {
|
||||
if let data = cert.certData where cert.key == nil {
|
||||
cert.key = self.extractPublicKey(data)
|
||||
}
|
||||
if let k = cert.key {
|
||||
collect.append(k)
|
||||
}
|
||||
}
|
||||
self.pubKeys = collect
|
||||
self.isReady = true
|
||||
})
|
||||
} else {
|
||||
var collect = Array<NSData>()
|
||||
for cert in certs {
|
||||
if let d = cert.certData {
|
||||
collect.append(d)
|
||||
}
|
||||
}
|
||||
self.certificates = collect
|
||||
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 {
|
||||
var trustedCount = 0
|
||||
let serverPubKeys = publicKeyChainForTrust(trust)
|
||||
for serverKey in serverPubKeys as [AnyObject] {
|
||||
for key in keys as [AnyObject] {
|
||||
if serverKey.isEqual(key) {
|
||||
trustedCount++
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if trustedCount == serverPubKeys.count {
|
||||
return true
|
||||
}
|
||||
}
|
||||
} else if let certs = self.certificates {
|
||||
let serverCerts = certificateChainForTrust(trust)
|
||||
var collect = Array<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? {
|
||||
let possibleCert = SecCertificateCreateWithData(nil,data)
|
||||
if let cert = possibleCert {
|
||||
return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/**
|
||||
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)
|
||||
if let trust = possibleTrust {
|
||||
var result: SecTrustResultType = 0
|
||||
SecTrustEvaluate(trust, &result)
|
||||
return SecTrustCopyPublicKey(trust)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/**
|
||||
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) -> Array<NSData> {
|
||||
var collect = Array<NSData>()
|
||||
for var i = 0; i < SecTrustGetCertificateCount(trust); i++ {
|
||||
let cert = SecTrustGetCertificateAtIndex(trust,i)
|
||||
collect.append(SecCertificateCopyData(cert!))
|
||||
}
|
||||
return collect
|
||||
}
|
||||
|
||||
/**
|
||||
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) -> Array<SecKeyRef> {
|
||||
var collect = Array<SecKeyRef>()
|
||||
let policy = SecPolicyCreateBasicX509()
|
||||
for var i = 0; i < SecTrustGetCertificateCount(trust); i++ {
|
||||
let cert = SecTrustGetCertificateAtIndex(trust,i)
|
||||
if let key = extractPublicKeyFromCert(cert!, policy: policy) {
|
||||
collect.append(key)
|
||||
}
|
||||
}
|
||||
return collect
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user