Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
94f02e567a | ||
|
|
4eca685dc2 | ||
|
|
90f512e03b | ||
|
|
7d8b0c89c5 | ||
|
|
e45003210f | ||
|
|
4d07d2911f | ||
|
|
0d6e4af62f | ||
|
|
2e6803bd1a | ||
|
|
bcb556b66c | ||
|
|
d8b5293ca1 | ||
|
|
ec2aa703a3 | ||
|
|
c211ab140d | ||
|
|
5cab7dbb2f | ||
|
|
0fc70e8be1 | ||
|
|
609ce08351 | ||
|
|
e366e808ae | ||
|
|
03d5f56114 | ||
|
|
2cf448de72 | ||
|
|
fb0c6a5612 | ||
|
|
a9633510ff | ||
|
|
95d2dce641 | ||
|
|
88b1eb1948 | ||
|
|
67f47ad6fe | ||
|
|
d6c521123b | ||
|
|
024384dc82 | ||
|
|
ec67056d2a | ||
|
|
15cfba46bc | ||
|
|
dbc8b6fadc | ||
|
|
d15fb90950 | ||
|
|
e06a792503 | ||
|
|
b202b21d43 | ||
|
|
443f5c5b22 | ||
|
|
3979b36f63 | ||
|
|
ac460d8023 | ||
|
|
731c8a851b | ||
|
|
a299901fa8 | ||
|
|
660aed8359 | ||
|
|
06aafa78ed | ||
|
|
3c9070b3e7 | ||
|
|
3587c20718 | ||
|
|
de3ca964ab | ||
|
|
19c68416bb | ||
|
|
ee5934de6a | ||
|
|
ca67625ed3 | ||
|
|
fe02b8eff2 | ||
|
|
0c8ff90537 | ||
|
|
5068986a50 | ||
|
|
4ed4681cc4 | ||
|
|
361cd8fc3b | ||
|
|
2916ed0f7b | ||
|
|
cfa98ea42b | ||
|
|
8584b90d3c | ||
|
|
7acce7d18e | ||
|
|
0ebe56d780 | ||
|
|
3d8867136d | ||
|
|
bed5ecd23b | ||
|
|
4e5fcff258 | ||
|
|
aeb52de72f | ||
|
|
ca90938675 | ||
|
|
1aacab2567 | ||
|
|
a28fda392c | ||
|
|
931382deff | ||
|
|
298817ce5c | ||
|
|
8cf3aebf9f | ||
|
|
75fc013f92 | ||
|
|
44c5591646 | ||
|
|
8e0d03b28c | ||
|
|
7b1f72852f | ||
|
|
97d4f3f527 | ||
|
|
d94a1901ca | ||
|
|
fff2f29c55 | ||
|
|
57d1f3c4b4 | ||
|
|
499c0d6824 | ||
|
|
85cf6c48b1 | ||
|
|
5848516c4e | ||
|
|
238d3cb338 | ||
|
|
275c873880 | ||
|
|
2ccaa4351a | ||
|
|
c642017f4b | ||
|
|
7b11e7c3e0 | ||
|
|
6e5b95be31 | ||
|
|
ccad13a1ed | ||
|
|
bb26ae8637 | ||
|
|
b9fd6c9d5b | ||
|
|
f001b8340c | ||
|
|
9b67549d25 | ||
|
|
e2f89d82e4 | ||
|
|
9c1a3edeb9 | ||
|
|
04d49fe7cb | ||
|
|
c74858fd5d | ||
|
|
0acb7421cc | ||
|
|
57b252fa7d | ||
|
|
87e12fd284 | ||
|
|
0470647d87 | ||
|
|
80a734e95f | ||
|
|
c26adae13c | ||
|
|
76375bbcf3 | ||
|
|
6199c2f914 | ||
|
|
e0c794cb9f | ||
|
|
db63aa63c2 | ||
|
|
9aec259d67 | ||
|
|
6e21fba469 | ||
|
|
38e08f17a2 | ||
|
|
71c78e1e12 | ||
|
|
b35004ef60 | ||
|
|
cf14eb27a3 | ||
|
|
0de8a65ff4 | ||
|
|
fe21fcc7e1 | ||
|
|
4be7bb0079 | ||
|
|
da5977ac31 | ||
|
|
bbb383da58 | ||
|
|
c818ed2c10 | ||
|
|
6e54ac4534 | ||
|
|
a87214cf06 | ||
|
|
8c405cee88 | ||
|
|
0b6cece96b | ||
|
|
9633bea018 | ||
|
|
d808ae18d2 | ||
|
|
f6dabf8f8e | ||
|
|
47fd0e386f | ||
|
|
9deb5a06a6 | ||
|
|
8f27b0d021 | ||
|
|
e137e66592 | ||
|
|
bba966a125 | ||
|
|
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 | ||
|
|
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 | ||
|
|
5a73a5e6da | ||
|
|
1f5402ce1c | ||
|
|
9510ef9d4f | ||
|
|
2a7ec38d48 | ||
|
|
ccd6dcbf0a | ||
|
|
4fdb49ea2f | ||
|
|
2351637ab4 | ||
|
|
58097fa39e | ||
|
|
4c9d6ef3de | ||
|
|
aa43107ad6 | ||
|
|
9c3d991bed | ||
|
|
09a26c0b1c | ||
|
|
f752507a11 | ||
|
|
2cafec6f12 | ||
|
|
7ebcd7439f | ||
|
|
5e92fc323d | ||
|
|
c2b927fd02 | ||
|
|
4014286da2 | ||
|
|
884b73c777 | ||
|
|
b563334d14 | ||
|
|
848f7e5da7 | ||
|
|
42aced5e9c | ||
|
|
b52684cb8f | ||
|
|
25464ffb9d | ||
|
|
d0f091e983 | ||
|
|
889ad404bc | ||
|
|
6fa7636261 | ||
|
|
5eeac96b2b | ||
|
|
f46629f850 | ||
|
|
84bb6b7dad | ||
|
|
145448c087 | ||
|
|
184b97ef8c | ||
|
|
d0ec1de566 | ||
|
|
643ddb5bf9 | ||
|
|
469caf1b54 | ||
|
|
63a257ac80 | ||
|
|
514193e6ec | ||
|
|
969e6d6ea8 | ||
|
|
80ea42c91f | ||
|
|
0308e274cd | ||
|
|
dd71d4954d | ||
|
|
06e2311acc | ||
|
|
2579c04f67 | ||
|
|
137fd1229b | ||
|
|
6650afd3e4 | ||
|
|
150e26aefd | ||
|
|
f0a45e13e2 | ||
|
|
7800591367 | ||
|
|
92367fc796 | ||
|
|
fbe3bd9b30 | ||
|
|
e25afd60fd | ||
|
|
f0b4f077d4 | ||
|
|
1b08411ed4 | ||
|
|
bf3e28df81 | ||
|
|
4086ce7d75 | ||
|
|
feea80a2f9 | ||
|
|
a0e3052893 | ||
|
|
79848b1ce0 | ||
|
|
30cf2bb67a | ||
|
|
b1b9a7edaf | ||
|
|
cf98f09b93 | ||
|
|
3c9c473e70 | ||
|
|
252181b0c5 | ||
|
|
a4988e6404 | ||
|
|
a1af98e173 | ||
|
|
aa6db7c837 | ||
|
|
a07916fb2f | ||
|
|
4b9db85a49 | ||
|
|
149e6137af | ||
|
|
224c660e4c | ||
|
|
7b795fd989 | ||
|
|
846f10eb13 | ||
|
|
94a3844181 | ||
|
|
01aa6354e3 | ||
|
|
a277e88c3b | ||
|
|
d073fa8a83 | ||
|
|
5057226a6c | ||
|
|
c21799abac | ||
|
|
68078e50d5 | ||
|
|
8daa7da426 | ||
|
|
24583f19c1 | ||
|
|
652c81a80e | ||
|
|
422b93f577 | ||
|
|
38a7cc8648 | ||
|
|
a22869efad | ||
|
|
6ecd1e2a79 | ||
|
|
b388df798b | ||
|
|
7206fa6d5c | ||
|
|
362f4e90b8 | ||
|
|
77eb1603ac | ||
|
|
eb00be0aaa | ||
|
|
9454a47ef4 | ||
|
|
bd88ff763b | ||
|
|
f41b64137e | ||
|
|
df2f149f85 | ||
|
|
f2ef3344c0 | ||
|
|
65be52418d | ||
|
|
76637d160e | ||
|
|
f2e5a1437b | ||
|
|
a0c676bc54 | ||
|
|
5854262280 | ||
|
|
1c8fcee772 | ||
|
|
11d8430537 | ||
|
|
a15b57e900 | ||
|
|
fafeebe185 | ||
|
|
66622fffb3 | ||
|
|
7bf35e182c | ||
|
|
78727dc0ee |
No files matched your search
@@ -1,6 +1,9 @@
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
*.xcodeproj
|
||||
.build/*
|
||||
Packages/*
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
@@ -41,3 +44,5 @@ 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
|
||||
@@ -0,0 +1,5 @@
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "SocketIOClientSwift"
|
||||
)
|
||||
@@ -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 {
|
||||
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,23 +54,41 @@ 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 Source 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.
|
||||
|
||||
Swift Package Manager
|
||||
---------------------
|
||||
Add the project as a dependency to your Package.swift:
|
||||
```swift
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "YourSocketIOProject",
|
||||
dependencies: [
|
||||
.Package(url: "https://github.com/socketio/socket.io-client-swift", majorVersion: 5)
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
Then import `import SocketIOClientSwift`.
|
||||
|
||||
Carthage
|
||||
-----------------
|
||||
Add this line to your `Cartfile`:
|
||||
```
|
||||
github "socketio/socket.io-client-swift" ~> 2.4.4 # Or latest version
|
||||
github "socketio/socket.io-client-swift" ~> 5.2.3 # Or latest version
|
||||
```
|
||||
|
||||
Run `carthage update`.
|
||||
|
||||
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.
|
||||
Run `carthage update --platform ios,macosx`.
|
||||
|
||||
CocoaPods 0.36.0 or later (iOS 8+)
|
||||
------------------
|
||||
@@ -79,7 +99,7 @@ source 'https://github.com/CocoaPods/Specs.git'
|
||||
platform :ios, '8.0'
|
||||
use_frameworks!
|
||||
|
||||
pod 'Socket.IO-Client-Swift', '~> 2.4.4' # Or latest version
|
||||
pod 'Socket.IO-Client-Swift', '~> 5.2.3' # Or latest version
|
||||
```
|
||||
|
||||
Install pods:
|
||||
@@ -92,51 +112,77 @@ Import the module:
|
||||
|
||||
Swift:
|
||||
```swift
|
||||
import Socket_IO_Client_Swift
|
||||
import SocketIOClientSwift
|
||||
```
|
||||
|
||||
Objective-C:
|
||||
|
||||
```Objective-C
|
||||
#import <Socket_IO_Client_Swift/Socket_IO_Client_Swift-Swift.h>
|
||||
#import <SocketIOClientSwift/SocketIOClientSwift-Swift.h>
|
||||
```
|
||||
|
||||
CocoaSeeds
|
||||
-----------------
|
||||
|
||||
Add this line to your `Seedfile`:
|
||||
|
||||
```
|
||||
github "socketio/socket.io-client-swift", "v5.2.3", :files => "Source/*.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> = [])` - 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 `""`
|
||||
- `extraHeaders: [String: String]?` - Adds custom headers to the initial request. Default is nil.
|
||||
- `handleQueue: dispatch_queue_t` - The dispatch queue that handlers are run on. Default is the main queue.
|
||||
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 ForceNew(Bool) // Will a create a new engine for each connect. Useful if you find a bug in the engine related to reconnects
|
||||
case ForceWebsockets(Bool) // `true` forces the client to use WebSockets. Default is `false`
|
||||
case Nsp(String) // The namespace to connect to. Must begin with /. Default is `/`
|
||||
case Cookies([NSHTTPCookie]) // An array of NSHTTPCookies. Passed during the handshake. Default is nil.
|
||||
case 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.
|
||||
case VoipEnabled(Bool) // Only use this option if you're using the client with VoIP services. Changes the way the WebSocket is created. Default is false
|
||||
case Secure(Bool) // If the connection should use TLS. Default is false.
|
||||
case SelfSigned(Bool) // Sets WebSocket.selfSignedSSL (Don't do this, iOS will yell at you)
|
||||
|
||||
```
|
||||
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...) -> (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.
|
||||
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) -> NSUUID` - 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. Returns a unique id for the handler.
|
||||
2. `once(event: String, callback: NormalCallback) -> NSUUID` - Adds a handler that will only be executed once. Returns a unique id for the handler.
|
||||
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. `disconnect()` - Closes the socket. Reopening a disconnected socket is not fully tested.
|
||||
11. `reconnect()` - Causes the client to reconnect to the server.
|
||||
12. `joinNamespace(namespace: String)` - Causes the client to join namespace. Shouldn't need to be called unless you change namespaces 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. `off(id id: NSUUID)` - Removes the event that corresponds to id.
|
||||
16. `removeAllHandlers()` - Removes all handlers.
|
||||
|
||||
Client Events
|
||||
------
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "Socket.IO-Client-Swift"
|
||||
s.version = "2.4.4"
|
||||
s.module_name = "SocketIOClientSwift"
|
||||
s.version = "5.2.3"
|
||||
s.summary = "Socket.IO-client for iOS and OS X"
|
||||
s.description = <<-DESC
|
||||
Socket.IO-client for iOS and OS X.
|
||||
Supports ws/wss/polling connections and binary.
|
||||
For socket.io 1.0+ and Swift 1.2.
|
||||
For socket.io 1.0+ and Swift.
|
||||
DESC
|
||||
s.homepage = "https://github.com/socketio/socket.io-client-swift"
|
||||
s.license = { :type => 'MIT' }
|
||||
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.4.4' }
|
||||
s.source_files = "SocketIOClientSwift/**/*.swift"
|
||||
s.tvos.deployment_target = '9.0'
|
||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v5.2.3' }
|
||||
s.source_files = "Source/**/*.swift"
|
||||
s.requires_arc = true
|
||||
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
|
||||
end
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0640"
|
||||
LastUpgradeVersion = "0720"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -15,7 +15,7 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BuildableName = "SocketIOClientSwift.framework"
|
||||
BlueprintName = "SocketIO-Mac"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
@@ -37,10 +37,10 @@
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Debug">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
@@ -57,26 +57,29 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BuildableName = "SocketIOClientSwift.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"
|
||||
buildConfiguration = "Debug"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BuildableName = "SocketIOClientSwift.framework"
|
||||
BlueprintName = "SocketIO-Mac"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
@@ -85,16 +88,16 @@
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Release"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BuildableName = "SocketIOClientSwift.framework"
|
||||
BlueprintName = "SocketIO-Mac"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0640"
|
||||
LastUpgradeVersion = "0720"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -15,7 +15,7 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BuildableName = "SocketIOClientSwift.framework"
|
||||
BlueprintName = "SocketIO-iOS"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
@@ -37,10 +37,11 @@
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Debug">
|
||||
codeCoverageEnabled = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
@@ -57,26 +58,29 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BuildableName = "SocketIOClientSwift.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"
|
||||
buildConfiguration = "Debug"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BuildableName = "SocketIOClientSwift.framework"
|
||||
BlueprintName = "SocketIO-iOS"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
@@ -85,16 +89,16 @@
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Release"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BuildableName = "SocketIOClientSwift.framework"
|
||||
BlueprintName = "SocketIO-iOS"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0720"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "576349FA1BD9B46A00E19CD7"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-tvOS"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "57634A181BD9B46D00E19CD7"
|
||||
BuildableName = "SocketIO-tvOSTests.xctest"
|
||||
BlueprintName = "SocketIO-tvOSTests"
|
||||
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 = "57634A181BD9B46D00E19CD7"
|
||||
BuildableName = "SocketIO-tvOSTests.xctest"
|
||||
BlueprintName = "SocketIO-tvOSTests"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "576349FA1BD9B46A00E19CD7"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-tvOS"
|
||||
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 = "576349FA1BD9B46A00E19CD7"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-tvOS"
|
||||
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 = "576349FA1BD9B46A00E19CD7"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-tvOS"
|
||||
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
|
||||
@@ -7,7 +7,7 @@
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>io.socket.$(PRODUCT_NAME:rfc1034identifier)</string>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>io.socket.$(PRODUCT_NAME:rfc1034identifier)</string>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
//
|
||||
// SocketAckManagerTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Lukas Schmidt on 04.09.15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import SocketIOClientSwift
|
||||
|
||||
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,140 @@
|
||||
//
|
||||
// SocketBasicPacketTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/7/15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import SocketIOClientSwift
|
||||
|
||||
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,77 @@
|
||||
//
|
||||
// SocketEngineTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/15/15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import SocketIOClientSwift
|
||||
|
||||
class SocketEngineTest: XCTestCase {
|
||||
var client: SocketIOClient!
|
||||
var engine: SocketEngine!
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
client = SocketIOClient(socketURL: "")
|
||||
engine = SocketEngine(client: client, url: "", 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)
|
||||
}
|
||||
|
||||
func testEngineDoesErrorOnUnknownTransport() {
|
||||
let finalExpectation = expectationWithDescription("Unknown Transport")
|
||||
|
||||
client.on("error") {data, ack in
|
||||
if let error = data[0] as? String where error == "Unknown transport" {
|
||||
finalExpectation.fulfill()
|
||||
}
|
||||
}
|
||||
|
||||
engine.parseEngineMessage("{\"code\": 0, \"message\": \"Unknown transport\"}", fromPolling: false)
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testEngineDoesErrorOnUnknownMessage() {
|
||||
let finalExpectation = expectationWithDescription("Engine Errors")
|
||||
|
||||
client.on("error") {data, ack in
|
||||
finalExpectation.fulfill()
|
||||
}
|
||||
|
||||
engine.parseEngineMessage("afafafda", fromPolling: false)
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
//
|
||||
// SocketIO_MacTests.swift
|
||||
// SocketIO-MacTests
|
||||
//
|
||||
// Created by Nacho Soto on 7/11/15.
|
||||
//
|
||||
//
|
||||
|
||||
import Cocoa
|
||||
import XCTest
|
||||
|
||||
class SocketIO_MacTests: XCTestCase {
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
// Put setup code here. This method is called before the invocation of each test method in the class.
|
||||
}
|
||||
|
||||
override func tearDown() {
|
||||
// Put teardown code here. This method is called after the invocation of each test method in the class.
|
||||
super.tearDown()
|
||||
}
|
||||
|
||||
func testExample() {
|
||||
// This is an example of a functional test case.
|
||||
XCTAssert(true, "Pass")
|
||||
}
|
||||
|
||||
func testPerformanceExample() {
|
||||
// This is an example of a performance test case.
|
||||
self.measureBlock() {
|
||||
// Put the code you want to measure the time of here.
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//
|
||||
// SocketNamespacePacketTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/11/15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import SocketIOClientSwift
|
||||
|
||||
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,136 @@
|
||||
//
|
||||
// SocketParserTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Lukas Schmidt on 05.09.15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import SocketIOClientSwift
|
||||
|
||||
class SocketParserTest: XCTestCase {
|
||||
let testSocket = SocketIOClient(socketURL: "")
|
||||
|
||||
//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 testSocket.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 = testSocket.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() {
|
||||
self.testSocket.parseString(item.element)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//
|
||||
// SocketSideEffectTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/11/15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import SocketIOClientSwift
|
||||
|
||||
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 testHandleAck2() {
|
||||
let expectation = expectationWithDescription("handled ack2")
|
||||
socket.emitWithAck("test")(timeoutAfter: 0) {data in
|
||||
XCTAssertTrue(data.count == 2, "Wrong number of ack items")
|
||||
expectation.fulfill()
|
||||
}
|
||||
|
||||
socket.parseSocketMessage("61-0[{\"_placeholder\":true,\"num\":0},{\"test\":true}]")
|
||||
socket.parseBinaryData(NSData())
|
||||
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 testHandleOnceEvent() {
|
||||
let expectation = expectationWithDescription("handled event")
|
||||
socket.once("test") {data, ack in
|
||||
XCTAssertEqual(data[0] as? String, "hello world")
|
||||
XCTAssertEqual(self.socket.testHandlers.count, 0)
|
||||
expectation.fulfill()
|
||||
}
|
||||
|
||||
socket.parseSocketMessage("2[\"test\",\"hello world\"]")
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testOffWithEvent() {
|
||||
socket.on("test") {data, ack in }
|
||||
XCTAssertEqual(socket.testHandlers.count, 1)
|
||||
socket.on("test") {data, ack in }
|
||||
XCTAssertEqual(socket.testHandlers.count, 2)
|
||||
socket.off("test")
|
||||
XCTAssertEqual(socket.testHandlers.count, 0)
|
||||
}
|
||||
|
||||
func testOffWithId() {
|
||||
let handler = socket.on("test") {data, ack in }
|
||||
XCTAssertEqual(socket.testHandlers.count, 1)
|
||||
socket.on("test") {data, ack in }
|
||||
XCTAssertEqual(socket.testHandlers.count, 2)
|
||||
socket.off(id: handler)
|
||||
XCTAssertEqual(socket.testHandlers.count, 1)
|
||||
}
|
||||
|
||||
func testHandlesErrorPacket() {
|
||||
let expectation = expectationWithDescription("Handled error")
|
||||
socket.on("error") {data, ack in
|
||||
if let error = data[0] as? String where error == "test error" {
|
||||
expectation.fulfill()
|
||||
}
|
||||
}
|
||||
|
||||
socket.parseSocketMessage("4\"test error\"")
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>io.socket.$(PRODUCT_NAME:rfc1034identifier)</string>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>io.socket.$(PRODUCT_NAME:rfc1034identifier)</string>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
//
|
||||
// SocketIO_iOSTests.swift
|
||||
// SocketIO-iOSTests
|
||||
//
|
||||
// Created by Nacho Soto on 7/11/15.
|
||||
//
|
||||
//
|
||||
|
||||
import UIKit
|
||||
import XCTest
|
||||
|
||||
class SocketIO_iOSTests: XCTestCase {
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
// Put setup code here. This method is called before the invocation of each test method in the class.
|
||||
}
|
||||
|
||||
override func tearDown() {
|
||||
// Put teardown code here. This method is called after the invocation of each test method in the class.
|
||||
super.tearDown()
|
||||
}
|
||||
|
||||
func testExample() {
|
||||
// This is an example of a functional test case.
|
||||
XCTAssert(true, "Pass")
|
||||
}
|
||||
|
||||
func testPerformanceExample() {
|
||||
// This is an example of a performance test case.
|
||||
self.measureBlock() {
|
||||
// Put the code you want to measure the time of here.
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,788 +0,0 @@
|
||||
//
|
||||
// SocketEngine.swift
|
||||
// Socket.IO-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/3/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 SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
private typealias Probe = (msg:String, type:PacketType, data:ContiguousArray<NSData>?)
|
||||
private typealias ProbeWaitQueue = [Probe]
|
||||
|
||||
private let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
|
||||
private let workQueue = NSOperationQueue()
|
||||
private let emitQueue = dispatch_queue_create("engineEmitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let parseQueue = dispatch_queue_create("engineParseQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let handleQueue = dispatch_queue_create("engineHandleQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let session:NSURLSession!
|
||||
|
||||
private var closed = false
|
||||
private var _connected = false
|
||||
private var extraHeaders:[String: String]?
|
||||
private var fastUpgrade = false
|
||||
private var forcePolling = false
|
||||
private var forceWebsockets = false
|
||||
private var pingInterval:Double?
|
||||
private var pingTimer:NSTimer?
|
||||
private var pingTimeout = 0.0 {
|
||||
didSet {
|
||||
pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25))
|
||||
}
|
||||
}
|
||||
private var pongsMissed = 0
|
||||
private var pongsMissedMax = 0
|
||||
private var postWait = [String]()
|
||||
private var _polling = true
|
||||
private var probing = false
|
||||
private var probeWait = ProbeWaitQueue()
|
||||
private var waitingForPoll = false
|
||||
private var waitingForPost = false
|
||||
private var _websocket = false
|
||||
private var websocketConnected = false
|
||||
|
||||
let logType = "SocketEngine"
|
||||
|
||||
var connected:Bool {
|
||||
return _connected
|
||||
}
|
||||
weak var client:SocketEngineClient?
|
||||
var cookies:[NSHTTPCookie]?
|
||||
var log = false
|
||||
var polling:Bool {
|
||||
return _polling
|
||||
}
|
||||
var sid = ""
|
||||
var socketPath = ""
|
||||
var urlPolling:String?
|
||||
var urlWebSocket:String?
|
||||
var websocket:Bool {
|
||||
return _websocket
|
||||
}
|
||||
var ws:WebSocket?
|
||||
|
||||
public enum PacketType:Int {
|
||||
case OPEN = 0
|
||||
case CLOSE = 1
|
||||
case PING = 2
|
||||
case PONG = 3
|
||||
case MESSAGE = 4
|
||||
case UPGRADE = 5
|
||||
case NOOP = 6
|
||||
|
||||
init?(str:String?) {
|
||||
if let value = str?.toInt(), raw = PacketType(rawValue: value) {
|
||||
self = raw
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public init(client:SocketEngineClient, sessionDelegate:NSURLSessionDelegate?) {
|
||||
self.client = client
|
||||
self.session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
|
||||
delegate: sessionDelegate, delegateQueue: workQueue)
|
||||
}
|
||||
|
||||
public convenience init(client:SocketEngineClient, opts:NSDictionary?) {
|
||||
self.init(client: client, sessionDelegate: opts?["sessionDelegate"] as? NSURLSessionDelegate)
|
||||
forceWebsockets = opts?["forceWebsockets"] as? Bool ?? false
|
||||
forcePolling = opts?["forcePolling"] as? Bool ?? false
|
||||
cookies = opts?["cookies"] as? [NSHTTPCookie]
|
||||
log = opts?["log"] as? Bool ?? false
|
||||
socketPath = opts?["path"] as? String ?? ""
|
||||
extraHeaders = opts?["extraHeaders"] as? [String: String]
|
||||
}
|
||||
|
||||
deinit {
|
||||
SocketLogger.log("Engine is being deinit", client: self)
|
||||
}
|
||||
|
||||
public func close(#fast:Bool) {
|
||||
SocketLogger.log("Engine is being closed. Fast: %@", client: self, args: fast)
|
||||
|
||||
pingTimer?.invalidate()
|
||||
closed = true
|
||||
|
||||
ws?.disconnect()
|
||||
|
||||
if fast || polling {
|
||||
write("", withType: PacketType.CLOSE, withData: nil)
|
||||
client?.engineDidClose("Disconnect")
|
||||
}
|
||||
|
||||
stopPolling()
|
||||
}
|
||||
|
||||
private func createBinaryDataForSend(data:NSData) -> (NSData?, String?) {
|
||||
if websocket {
|
||||
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
|
||||
byteArray[0] = 4
|
||||
var mutData = NSMutableData(bytes: &byteArray, length: 1)
|
||||
|
||||
mutData.appendData(data)
|
||||
|
||||
return (mutData, nil)
|
||||
} else {
|
||||
var str = "b4"
|
||||
str += data.base64EncodedStringWithOptions(
|
||||
NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
|
||||
|
||||
return (nil, str)
|
||||
}
|
||||
}
|
||||
|
||||
private func createURLs(params:[String: AnyObject]?) -> (String?, String?) {
|
||||
if client == nil {
|
||||
return (nil, nil)
|
||||
}
|
||||
|
||||
let path = socketPath == "" ? "/socket.io" : socketPath
|
||||
|
||||
var url = "\(client!.socketURL)\(path)/?transport="
|
||||
var urlPolling:String
|
||||
var urlWebSocket:String
|
||||
|
||||
if client!.secure {
|
||||
urlPolling = "https://" + url + "polling"
|
||||
urlWebSocket = "wss://" + url + "websocket"
|
||||
} else {
|
||||
urlPolling = "http://" + url + "polling"
|
||||
urlWebSocket = "ws://" + url + "websocket"
|
||||
}
|
||||
|
||||
if params != nil {
|
||||
|
||||
for (key, value) in params! {
|
||||
let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters(
|
||||
allowedCharacterSet)!
|
||||
urlPolling += "&\(keyEsc)="
|
||||
urlWebSocket += "&\(keyEsc)="
|
||||
|
||||
if value is String {
|
||||
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
|
||||
allowedCharacterSet)!
|
||||
urlPolling += "\(valueEsc)"
|
||||
urlWebSocket += "\(valueEsc)"
|
||||
} else {
|
||||
urlPolling += "\(value)"
|
||||
urlWebSocket += "\(value)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (urlPolling, urlWebSocket)
|
||||
}
|
||||
|
||||
private func createWebsocket(andConnect connect:Bool) {
|
||||
let wsUrl = urlWebSocket! + (sid == "" ? "" : "&sid=\(sid)")
|
||||
|
||||
ws = WebSocket(url: NSURL(string: wsUrl)!,
|
||||
cookies: cookies)
|
||||
|
||||
if extraHeaders != nil {
|
||||
for (headerName, value) in extraHeaders! {
|
||||
ws?.headers[headerName] = value
|
||||
}
|
||||
}
|
||||
|
||||
ws?.queue = handleQueue
|
||||
ws?.delegate = self
|
||||
|
||||
if connect {
|
||||
ws?.connect()
|
||||
}
|
||||
}
|
||||
|
||||
private func doFastUpgrade() {
|
||||
if waitingForPoll {
|
||||
SocketLogger.err("Outstanding poll when switched to WebSockets," +
|
||||
"we'll probably disconnect soon. You should report this.", client: self)
|
||||
}
|
||||
|
||||
sendWebSocketMessage("", withType: PacketType.UPGRADE, datas: nil)
|
||||
_websocket = true
|
||||
_polling = false
|
||||
fastUpgrade = false
|
||||
probing = false
|
||||
flushProbeWait()
|
||||
}
|
||||
|
||||
private func doPoll() {
|
||||
if websocket || waitingForPoll || !connected {
|
||||
return
|
||||
}
|
||||
|
||||
waitingForPoll = true
|
||||
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&sid=\(sid)&b64=1")!)
|
||||
|
||||
if cookies != nil {
|
||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
|
||||
req.allHTTPHeaderFields = headers
|
||||
}
|
||||
|
||||
if extraHeaders != nil {
|
||||
for (headerName, value) in extraHeaders! {
|
||||
req.setValue(value, forHTTPHeaderField: headerName)
|
||||
}
|
||||
}
|
||||
|
||||
doRequest(req)
|
||||
}
|
||||
|
||||
private func doRequest(req:NSMutableURLRequest) {
|
||||
if !polling {
|
||||
return
|
||||
}
|
||||
|
||||
req.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
|
||||
|
||||
SocketLogger.log("Doing polling request", client: self)
|
||||
|
||||
session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
||||
if let this = self {
|
||||
if err != nil {
|
||||
if this.polling {
|
||||
this.handlePollingFailed(err.localizedDescription)
|
||||
} else {
|
||||
SocketLogger.err(err.localizedDescription, client: this)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
SocketLogger.log("Got polling response", client: this)
|
||||
|
||||
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
|
||||
dispatch_async(this.parseQueue) {[weak this] in
|
||||
this?.parsePollingMessage(str)
|
||||
}
|
||||
}
|
||||
|
||||
this.waitingForPoll = false
|
||||
|
||||
if this.fastUpgrade {
|
||||
this.doFastUpgrade()
|
||||
} else if !this.closed && this.polling {
|
||||
this.doPoll()
|
||||
}
|
||||
}}.resume()
|
||||
}
|
||||
|
||||
private func flushProbeWait() {
|
||||
SocketLogger.log("Flushing probe wait", client: self)
|
||||
|
||||
dispatch_async(emitQueue) {[weak self] in
|
||||
if let this = self {
|
||||
for waiter in this.probeWait {
|
||||
this.write(waiter.msg, withType: waiter.type, withData: waiter.data)
|
||||
}
|
||||
|
||||
this.probeWait.removeAll(keepCapacity: false)
|
||||
|
||||
if this.postWait.count != 0 {
|
||||
this.flushWaitingForPostToWebSocket()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func flushWaitingForPost() {
|
||||
if postWait.count == 0 || !connected {
|
||||
return
|
||||
} else if websocket {
|
||||
flushWaitingForPostToWebSocket()
|
||||
return
|
||||
}
|
||||
|
||||
var postStr = ""
|
||||
|
||||
for packet in postWait {
|
||||
let len = count(packet)
|
||||
|
||||
postStr += "\(len):\(packet)"
|
||||
}
|
||||
|
||||
postWait.removeAll(keepCapacity: false)
|
||||
|
||||
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&sid=\(sid)")!)
|
||||
|
||||
if cookies != nil {
|
||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
|
||||
req.allHTTPHeaderFields = headers
|
||||
}
|
||||
|
||||
req.HTTPMethod = "POST"
|
||||
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
|
||||
|
||||
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
|
||||
allowLossyConversion: false)!
|
||||
|
||||
req.HTTPBody = postData
|
||||
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
|
||||
|
||||
waitingForPost = true
|
||||
|
||||
SocketLogger.log("POSTing: %@", client: self, args: postStr)
|
||||
|
||||
session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
||||
if let this = self {
|
||||
if err != nil && this.polling {
|
||||
this.handlePollingFailed(err.localizedDescription)
|
||||
return
|
||||
} else if err != nil {
|
||||
NSLog(err.localizedDescription)
|
||||
return
|
||||
}
|
||||
|
||||
this.waitingForPost = false
|
||||
|
||||
dispatch_async(this.emitQueue) {[weak this] in
|
||||
if !(this?.fastUpgrade ?? true) {
|
||||
this?.flushWaitingForPost()
|
||||
this?.doPoll()
|
||||
}
|
||||
}
|
||||
}}.resume()
|
||||
}
|
||||
|
||||
// We had packets waiting for send when we upgraded
|
||||
// Send them raw
|
||||
private func flushWaitingForPostToWebSocket() {
|
||||
for msg in postWait {
|
||||
ws?.writeString(msg)
|
||||
}
|
||||
|
||||
postWait.removeAll(keepCapacity: true)
|
||||
}
|
||||
|
||||
private func handleClose() {
|
||||
if polling {
|
||||
client?.engineDidClose("Disconnect")
|
||||
}
|
||||
}
|
||||
|
||||
private func checkIfMessageIsBase64Binary(var message:String) {
|
||||
if message.hasPrefix("b4") {
|
||||
// binary in base64 string
|
||||
message.removeRange(Range<String.Index>(start: message.startIndex,
|
||||
end: advance(message.startIndex, 2)))
|
||||
|
||||
if let data = NSData(base64EncodedString: message,
|
||||
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters), client = client {
|
||||
dispatch_async(client.handleQueue) {[weak self] in
|
||||
self?.client?.parseBinaryData(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func handleMessage(message:String) {
|
||||
if let client = client {
|
||||
dispatch_async(client.handleQueue) {[weak client] in
|
||||
client?.parseSocketMessage(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func handleNOOP() {
|
||||
doPoll()
|
||||
}
|
||||
|
||||
private func handleOpen(openData:String) {
|
||||
var err:NSError?
|
||||
let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
|
||||
|
||||
if let json = NSJSONSerialization.JSONObjectWithData(mesData,
|
||||
options: NSJSONReadingOptions.AllowFragments,
|
||||
error: &err) as? NSDictionary, sid = json["sid"] as? String {
|
||||
let upgradeWs: Bool
|
||||
|
||||
self.sid = sid
|
||||
_connected = true
|
||||
|
||||
if let upgrades = json["upgrades"] as? [String] {
|
||||
upgradeWs = upgrades.filter {$0 == "websocket"}.count != 0
|
||||
} else {
|
||||
upgradeWs = false
|
||||
}
|
||||
|
||||
if let pingInterval = json["pingInterval"] as? Double, pingTimeout = json["pingTimeout"] as? Double {
|
||||
self.pingInterval = pingInterval / 1000.0
|
||||
self.pingTimeout = pingTimeout / 1000.0
|
||||
}
|
||||
|
||||
if !forcePolling && !forceWebsockets && upgradeWs {
|
||||
createWebsocket(andConnect: true)
|
||||
}
|
||||
} else {
|
||||
client?.didError("Engine failed to handshake")
|
||||
return
|
||||
}
|
||||
|
||||
startPingTimer()
|
||||
|
||||
if !forceWebsockets {
|
||||
doPoll()
|
||||
}
|
||||
}
|
||||
|
||||
private func handlePong(pongMessage:String) {
|
||||
pongsMissed = 0
|
||||
|
||||
// We should upgrade
|
||||
if pongMessage == "3probe" {
|
||||
upgradeTransport()
|
||||
}
|
||||
}
|
||||
|
||||
// A poll failed, tell the client about it
|
||||
private func handlePollingFailed(reason:String) {
|
||||
_connected = false
|
||||
ws?.disconnect()
|
||||
pingTimer?.invalidate()
|
||||
waitingForPoll = false
|
||||
waitingForPost = false
|
||||
|
||||
// If cancelled we were already closing
|
||||
if client == nil || reason == "cancelled" {
|
||||
return
|
||||
}
|
||||
|
||||
if !closed {
|
||||
client?.didError(reason)
|
||||
client?.engineDidClose(reason)
|
||||
}
|
||||
}
|
||||
|
||||
public func open(opts:[String: AnyObject]? = nil) {
|
||||
if connected {
|
||||
SocketLogger.err("Tried to open while connected", client: self)
|
||||
|
||||
client?.didError("Tried to open while connected")
|
||||
return
|
||||
}
|
||||
|
||||
SocketLogger.log("Starting engine", client: self)
|
||||
SocketLogger.log("Handshaking", client: self)
|
||||
|
||||
closed = false
|
||||
|
||||
(urlPolling, urlWebSocket) = createURLs(opts)
|
||||
|
||||
if forceWebsockets {
|
||||
_polling = false
|
||||
_websocket = true
|
||||
createWebsocket(andConnect: true)
|
||||
return
|
||||
}
|
||||
|
||||
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&b64=1")!)
|
||||
|
||||
if cookies != nil {
|
||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
|
||||
reqPolling.allHTTPHeaderFields = headers
|
||||
}
|
||||
|
||||
if extraHeaders != nil {
|
||||
for (headerName, value) in extraHeaders! {
|
||||
reqPolling.setValue(value, forHTTPHeaderField: headerName)
|
||||
}
|
||||
}
|
||||
|
||||
doRequest(reqPolling)
|
||||
}
|
||||
|
||||
// Translatation of engine.io-parser#decodePayload
|
||||
private func parsePollingMessage(str:String) {
|
||||
if count(str) == 1 {
|
||||
return
|
||||
}
|
||||
|
||||
// println(str)
|
||||
|
||||
let strArray = Array(str)
|
||||
var length = ""
|
||||
var n = 0
|
||||
var msg = ""
|
||||
|
||||
func testLength(length:String, inout n:Int) -> Bool {
|
||||
if let num = length.toInt() {
|
||||
n = num
|
||||
return false
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
for var i = 0, l = count(str); i < l; i++ {
|
||||
let chr = String(strArray[i])
|
||||
|
||||
if chr != ":" {
|
||||
length += chr
|
||||
} else {
|
||||
if length == "" || testLength(length, &n) {
|
||||
SocketLogger.err("Parsing error: %@", client: self, args: str)
|
||||
handlePollingFailed("Error parsing XHR message")
|
||||
return
|
||||
}
|
||||
|
||||
msg = String(strArray[i+1...i+n])
|
||||
|
||||
if let lengthInt = length.toInt() where lengthInt != count(msg) {
|
||||
SocketLogger.err("Parsing error: %@", client: self, args: str)
|
||||
return
|
||||
}
|
||||
|
||||
if count(msg) != 0 {
|
||||
// Be sure to capture the value of the msg
|
||||
dispatch_async(handleQueue) {[weak self, msg] in
|
||||
self?.parseEngineMessage(msg, fromPolling: true)
|
||||
}
|
||||
}
|
||||
|
||||
i += n
|
||||
length = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func parseEngineData(data:NSData) {
|
||||
if let client = client {
|
||||
dispatch_async(client.handleQueue) {[weak self] in
|
||||
self?.client?.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func parseEngineMessage(var message:String, fromPolling:Bool) {
|
||||
SocketLogger.log("Got message: %@", client: self, args: message)
|
||||
|
||||
if fromPolling {
|
||||
fixDoubleUTF8(&message)
|
||||
}
|
||||
|
||||
let type = PacketType(str: (message["^(\\d)"].groups()?[1])) ?? {
|
||||
self.checkIfMessageIsBase64Binary(message)
|
||||
return PacketType.NOOP
|
||||
}()
|
||||
|
||||
switch type {
|
||||
case PacketType.MESSAGE:
|
||||
message.removeAtIndex(message.startIndex)
|
||||
handleMessage(message)
|
||||
case PacketType.NOOP:
|
||||
handleNOOP()
|
||||
case PacketType.PONG:
|
||||
handlePong(message)
|
||||
case PacketType.OPEN:
|
||||
message.removeAtIndex(message.startIndex)
|
||||
handleOpen(message)
|
||||
case PacketType.CLOSE:
|
||||
handleClose()
|
||||
default:
|
||||
SocketLogger.log("Got unknown packet type", client: self)
|
||||
}
|
||||
}
|
||||
|
||||
private func probeWebSocket() {
|
||||
if websocketConnected {
|
||||
sendWebSocketMessage("probe", withType: PacketType.PING)
|
||||
}
|
||||
}
|
||||
|
||||
/// Send an engine message (4)
|
||||
public func send(msg:String, withData datas:ContiguousArray<NSData>?) {
|
||||
if probing {
|
||||
probeWait.append((msg, PacketType.MESSAGE, datas))
|
||||
} else {
|
||||
write(msg, withType: PacketType.MESSAGE, withData: datas)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func sendPing() {
|
||||
//Server is not responding
|
||||
if pongsMissed > pongsMissedMax {
|
||||
pingTimer?.invalidate()
|
||||
client?.engineDidClose("Ping timeout")
|
||||
return
|
||||
}
|
||||
|
||||
++pongsMissed
|
||||
write("", withType: PacketType.PING, withData: nil)
|
||||
}
|
||||
|
||||
/// Send polling message.
|
||||
/// Only call on emitQueue
|
||||
private func sendPollMessage(var msg:String, withType type:PacketType,
|
||||
datas:ContiguousArray<NSData>? = nil) {
|
||||
SocketLogger.log("Sending poll: %@ as type: %@", client: self, args: msg, type.rawValue)
|
||||
|
||||
doubleEncodeUTF8(&msg)
|
||||
let strMsg = "\(type.rawValue)\(msg)"
|
||||
|
||||
postWait.append(strMsg)
|
||||
|
||||
if datas != nil {
|
||||
for data in datas! {
|
||||
let (nilData, b64Data) = createBinaryDataForSend(data)
|
||||
|
||||
postWait.append(b64Data!)
|
||||
}
|
||||
}
|
||||
|
||||
if !waitingForPost {
|
||||
flushWaitingForPost()
|
||||
}
|
||||
}
|
||||
|
||||
/// Send message on WebSockets
|
||||
/// Only call on emitQueue
|
||||
private func sendWebSocketMessage(str:String, withType type:PacketType,
|
||||
datas:ContiguousArray<NSData>? = nil) {
|
||||
SocketLogger.log("Sending ws: %@ as type: %@", client: self, args: str, type.rawValue)
|
||||
|
||||
ws?.writeString("\(type.rawValue)\(str)")
|
||||
|
||||
if datas != nil {
|
||||
for data in datas! {
|
||||
let (data, nilString) = createBinaryDataForSend(data)
|
||||
if data != nil {
|
||||
ws?.writeData(data!)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Starts the ping timer
|
||||
private func startPingTimer() {
|
||||
if pingInterval == nil {
|
||||
return
|
||||
}
|
||||
|
||||
pingTimer?.invalidate()
|
||||
dispatch_async(dispatch_get_main_queue()) {[weak self] in
|
||||
if let this = self {
|
||||
this.pingTimer = NSTimer.scheduledTimerWithTimeInterval(this.pingInterval!, target: this,
|
||||
selector: Selector("sendPing"), userInfo: nil, repeats: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func stopPolling() {
|
||||
session.invalidateAndCancel()
|
||||
}
|
||||
|
||||
private func upgradeTransport() {
|
||||
if websocketConnected {
|
||||
SocketLogger.log("Upgrading transport to WebSockets", client: self)
|
||||
|
||||
fastUpgrade = true
|
||||
sendPollMessage("", withType: PacketType.NOOP)
|
||||
// After this point, we should not send anymore polling messages
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Write a message, independent of transport.
|
||||
*/
|
||||
public func write(msg:String, withType type:PacketType, withData data:ContiguousArray<NSData>?) {
|
||||
dispatch_async(emitQueue) {[weak self] in
|
||||
if let this = self where this.connected {
|
||||
if this.websocket {
|
||||
SocketLogger.log("Writing ws: %@ has data: %@", client: this,
|
||||
args: msg, data == nil ? false : true)
|
||||
this.sendWebSocketMessage(msg, withType: type, datas: data)
|
||||
} else {
|
||||
SocketLogger.log("Writing poll: %@ has data: %@", client: this,
|
||||
args: msg, data == nil ? false : true)
|
||||
this.sendPollMessage(msg, withType: type, datas: data)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Write a message, independent of transport. For Objective-C. withData should be an NSArray of NSData
|
||||
*/
|
||||
public func writeObjc(msg:String, withType type:Int, withData data:NSArray?) {
|
||||
if let pType = PacketType(rawValue: type) {
|
||||
var arr = ContiguousArray<NSData>()
|
||||
|
||||
if data != nil {
|
||||
for d in data! {
|
||||
arr.append(d as! NSData)
|
||||
}
|
||||
}
|
||||
|
||||
write(msg, withType: pType, withData: arr)
|
||||
}
|
||||
}
|
||||
|
||||
// Delagate methods
|
||||
|
||||
public func websocketDidConnect(socket:WebSocket) {
|
||||
websocketConnected = true
|
||||
|
||||
if !forceWebsockets {
|
||||
probing = true
|
||||
probeWebSocket()
|
||||
} else {
|
||||
_connected = true
|
||||
probing = false
|
||||
_polling = false
|
||||
}
|
||||
}
|
||||
|
||||
public func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
|
||||
websocketConnected = false
|
||||
probing = false
|
||||
|
||||
if closed {
|
||||
client?.engineDidClose("Disconnect")
|
||||
return
|
||||
}
|
||||
|
||||
if websocket {
|
||||
pingTimer?.invalidate()
|
||||
_connected = false
|
||||
_websocket = false
|
||||
|
||||
let reason = error?.localizedDescription ?? "Socket Disconnected"
|
||||
|
||||
if error != nil {
|
||||
client?.didError(reason)
|
||||
}
|
||||
|
||||
client?.engineDidClose(reason)
|
||||
} else {
|
||||
flushProbeWait()
|
||||
}
|
||||
}
|
||||
|
||||
public func websocketDidReceiveMessage(socket:WebSocket, text:String) {
|
||||
parseEngineMessage(text, fromPolling: false)
|
||||
}
|
||||
|
||||
public func websocketDidReceiveData(socket:WebSocket, data:NSData) {
|
||||
parseEngineData(data)
|
||||
}
|
||||
}
|
||||
@@ -1,536 +0,0 @@
|
||||
//
|
||||
// SocketIOClient.swift
|
||||
// Socket.IO-Swift
|
||||
//
|
||||
// Created by Erik Little on 11/23/14.
|
||||
//
|
||||
// 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 SocketIOClient: NSObject, SocketEngineClient, SocketLogClient {
|
||||
private var anyHandler:((SocketAnyEvent) -> Void)?
|
||||
private var _closed = false
|
||||
private var _connected = false
|
||||
private var _connecting = false
|
||||
private var currentReconnectAttempt = 0
|
||||
private var handlers = ContiguousArray<SocketEventHandler>()
|
||||
private var connectParams:[String: AnyObject]?
|
||||
private var _secure = false
|
||||
private var _reconnecting = false
|
||||
private var reconnectTimer:NSTimer?
|
||||
|
||||
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_attr_t!
|
||||
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 engine?.sid
|
||||
}
|
||||
|
||||
/**
|
||||
Create a new SocketIOClient. opts can be omitted
|
||||
*/
|
||||
public init(var socketURL:String, opts:[String: AnyObject]? = nil) {
|
||||
if socketURL["https://"].matches().count != 0 {
|
||||
self._secure = true
|
||||
}
|
||||
|
||||
socketURL = socketURL["http://"] ~= ""
|
||||
socketURL = socketURL["https://"] ~= ""
|
||||
|
||||
self.socketURL = socketURL
|
||||
self.opts = opts
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
if let handleQueue = opts?["handleQueue"] as? dispatch_queue_t {
|
||||
self.handleQueue = handleQueue
|
||||
} else {
|
||||
self.handleQueue = dispatch_get_main_queue()
|
||||
}
|
||||
|
||||
super.init()
|
||||
}
|
||||
|
||||
public convenience init(socketURL:String, options:[String: AnyObject]?) {
|
||||
self.init(socketURL: socketURL, opts: options)
|
||||
}
|
||||
|
||||
deinit {
|
||||
SocketLogger.log("Client is being deinit", client: self)
|
||||
engine?.close(fast: true)
|
||||
}
|
||||
|
||||
private func addEngine() {
|
||||
SocketLogger.log("Adding engine", client: self)
|
||||
|
||||
engine = SocketEngine(client: self, opts: opts)
|
||||
}
|
||||
|
||||
private func clearReconnectTimer() {
|
||||
reconnectTimer?.invalidate()
|
||||
reconnectTimer = nil
|
||||
}
|
||||
|
||||
/**
|
||||
Closes the socket. Only reopen the same socket if you know what you're doing.
|
||||
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)
|
||||
|
||||
reconnects = false
|
||||
_connecting = false
|
||||
_connected = false
|
||||
_reconnecting = false
|
||||
engine?.close(fast: fast)
|
||||
}
|
||||
|
||||
/**
|
||||
Connect to the server.
|
||||
*/
|
||||
public func connect() {
|
||||
connect(timeoutAfter: 0, withTimeoutHandler: nil)
|
||||
}
|
||||
|
||||
/**
|
||||
Connect to the server. If we aren't connected after timeoutAfter, call handler
|
||||
*/
|
||||
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
|
||||
}
|
||||
|
||||
_connecting = true
|
||||
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?()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func createOnAck(event:String, 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)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func didConnect() {
|
||||
SocketLogger.log("Socket connected", client: self)
|
||||
|
||||
_closed = false
|
||||
_connected = true
|
||||
_connecting = false
|
||||
_reconnecting = false
|
||||
currentReconnectAttempt = 0
|
||||
clearReconnectTimer()
|
||||
|
||||
// Don't handle as internal because something crazy could happen where
|
||||
// we disconnect before it's handled
|
||||
handleEvent("connect", data: nil, isInternalMessage: false)
|
||||
}
|
||||
|
||||
func didDisconnect(reason:String) {
|
||||
if closed {
|
||||
return
|
||||
}
|
||||
|
||||
SocketLogger.log("Disconnected: %@", client: self, args: reason)
|
||||
|
||||
_closed = true
|
||||
_connected = false
|
||||
reconnects = false
|
||||
_connecting = false
|
||||
_reconnecting = false
|
||||
|
||||
// Make sure the engine is actually dead.
|
||||
engine?.close(fast: true)
|
||||
handleEvent("disconnect", data: [reason], isInternalMessage: true)
|
||||
}
|
||||
|
||||
/// error
|
||||
public func didError(reason:AnyObject) {
|
||||
SocketLogger.err("%@", client: self, args: reason)
|
||||
|
||||
handleEvent("error", data: reason as? [AnyObject] ?? [reason],
|
||||
isInternalMessage: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Same as close
|
||||
*/
|
||||
public func disconnect(#fast:Bool) {
|
||||
close(fast: fast)
|
||||
}
|
||||
|
||||
/**
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Same as emit, but meant for Objective-C
|
||||
*/
|
||||
public func emit(event:String, withItems items:[AnyObject]) {
|
||||
if !connected {
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(emitQueue) {[weak self] in
|
||||
self?._emit(event, items)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
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)
|
||||
}
|
||||
|
||||
private func _emit(event:String, _ args:[AnyObject], ack:Int? = nil) {
|
||||
if !connected {
|
||||
return
|
||||
}
|
||||
|
||||
let packet = SocketPacket(type: nil, data: args, nsp: nsp, id: ack)
|
||||
let str:String
|
||||
|
||||
SocketParser.parseForEmit(packet)
|
||||
str = packet.createMessageForEvent(event)
|
||||
|
||||
SocketLogger.log("Emitting: %@", client: self, args: str)
|
||||
|
||||
if packet.type == SocketPacket.PacketType.BINARY_EVENT {
|
||||
engine?.send(str, withData: packet.binary)
|
||||
} else {
|
||||
engine?.send(str, withData: nil)
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
SocketParser.parseForEmit(packet)
|
||||
str = packet.createAck()
|
||||
|
||||
SocketLogger.log("Emitting Ack: %@", client: this, args: str)
|
||||
|
||||
if packet.type == SocketPacket.PacketType.BINARY_ACK {
|
||||
this.engine?.send(str, withData: packet.binary)
|
||||
} else {
|
||||
this.engine?.send(str, withData: nil)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func engineDidClose(reason:String) {
|
||||
_connected = false
|
||||
_connecting = false
|
||||
|
||||
if closed || !reconnects {
|
||||
didDisconnect(reason)
|
||||
} else if !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 ?? "")
|
||||
|
||||
ackHandlers.executeAck(ack,
|
||||
items: (data as? [AnyObject]?) ?? (data != nil ? [data!] : nil))
|
||||
}
|
||||
|
||||
/**
|
||||
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 {
|
||||
return
|
||||
}
|
||||
|
||||
SocketLogger.log("Handling event: %@ with data: %@", client: self,
|
||||
args: event, data ?? "")
|
||||
|
||||
if anyHandler != nil {
|
||||
dispatch_async(handleQueue) {[weak self] in
|
||||
self?.anyHandler?(SocketAnyEvent(event: event, items: data))
|
||||
}
|
||||
}
|
||||
|
||||
for handler in handlers {
|
||||
if handler.event == event {
|
||||
if ack != nil {
|
||||
dispatch_async(handleQueue) {[weak self] in
|
||||
handler.executeCallback(data, withAck: ack!, withSocket: self)
|
||||
}
|
||||
} else {
|
||||
dispatch_async(handleQueue) {[weak self] in
|
||||
handler.executeCallback(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Leaves nsp and goes back to /
|
||||
*/
|
||||
public func leaveNamespace() {
|
||||
if nsp != "/" {
|
||||
engine?.send("1/\(nsp)", withData: nil)
|
||||
nsp = "/"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Joins nsp if it is not /
|
||||
*/
|
||||
public func joinNamespace() {
|
||||
SocketLogger.log("Joining namespace", client: self)
|
||||
|
||||
if nsp != "/" {
|
||||
engine?.send("0/\(nsp)", withData: nil)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Removes handler(s)
|
||||
*/
|
||||
public func off(event:String) {
|
||||
SocketLogger.log("Removing handler for event: %@", client: self, args: event)
|
||||
|
||||
handlers = handlers.filter {$0.event == event ? false : true}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler for an event.
|
||||
*/
|
||||
public func on(event:String, callback:NormalCallback) {
|
||||
SocketLogger.log("Adding handler for event: %@", client: self, args: event)
|
||||
|
||||
let handler = SocketEventHandler(event: event, callback: callback)
|
||||
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) {
|
||||
anyHandler = handler
|
||||
}
|
||||
|
||||
/**
|
||||
Same as connect
|
||||
*/
|
||||
public func open() {
|
||||
connect()
|
||||
}
|
||||
|
||||
public func parseSocketMessage(msg:String) {
|
||||
SocketParser.parseSocketMessage(msg, socket: self)
|
||||
}
|
||||
|
||||
public func parseBinaryData(data:NSData) {
|
||||
SocketParser.parseBinaryData(data, socket: self)
|
||||
}
|
||||
|
||||
/**
|
||||
Trieds 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 || !reconnects {
|
||||
clearReconnectTimer()
|
||||
didDisconnect("Reconnect Failed")
|
||||
|
||||
return
|
||||
} else if connected {
|
||||
_connecting = false
|
||||
_reconnecting = false
|
||||
return
|
||||
}
|
||||
|
||||
if reconnectTimer == nil {
|
||||
SocketLogger.log("Starting reconnect", client: self)
|
||||
|
||||
_reconnecting = true
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SocketLogger.log("Trying to reconnect", client: self)
|
||||
handleEvent("reconnectAttempt", data: [reconnectAttempts - currentReconnectAttempt],
|
||||
isInternalMessage: true)
|
||||
|
||||
currentReconnectAttempt++
|
||||
connect()
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
//
|
||||
// SocketLogger.swift
|
||||
// SocketIO-Swift
|
||||
//
|
||||
// Created by Erik Little on 4/11/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
|
||||
|
||||
private let MESSAGE_LENGTH_MAX = 10000
|
||||
|
||||
protocol SocketLogClient {
|
||||
var log:Bool {get set}
|
||||
var logType:String {get}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
static func err(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("ERROR %@: %@", altType ?? type, replaced)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,237 +0,0 @@
|
||||
//
|
||||
// SocketPacket.swift
|
||||
// Socket.IO-Swift
|
||||
//
|
||||
// Created by Erik Little on 1/18/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
|
||||
|
||||
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?
|
||||
|
||||
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
|
||||
|
||||
init?(str:String) {
|
||||
if let int = str.toInt(), raw = PacketType(rawValue: int) {
|
||||
self = raw
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func getEvent() -> String {
|
||||
let event: AnyObject? = data?.removeAtIndex(0)
|
||||
|
||||
return event as? String ?? String(stringInterpolationSegment: event!)
|
||||
}
|
||||
|
||||
func addData(data:NSData) -> Bool {
|
||||
if placeholders == currentPlace {
|
||||
return true
|
||||
}
|
||||
|
||||
binary.append(data)
|
||||
currentPlace++
|
||||
|
||||
if placeholders == currentPlace {
|
||||
currentPlace = 0
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
return message + "]"
|
||||
} else if !ack {
|
||||
message += ","
|
||||
}
|
||||
|
||||
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 + ","
|
||||
} else if var str = arg as? String {
|
||||
str = str["\n"] ~= "\\\\n"
|
||||
str = str["\r"] ~= "\\\\r"
|
||||
|
||||
message += "\"\(str)\","
|
||||
} else if arg is NSNull {
|
||||
message += "null,"
|
||||
} else {
|
||||
message += "\(arg),"
|
||||
}
|
||||
}
|
||||
|
||||
if message != "" {
|
||||
message.removeAtIndex(message.endIndex.predecessor())
|
||||
}
|
||||
|
||||
return message + "]"
|
||||
}
|
||||
|
||||
func fillInPlaceholders() {
|
||||
var newArr = NSMutableArray(array: data!)
|
||||
|
||||
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])
|
||||
}
|
||||
}
|
||||
|
||||
data = newArr as [AnyObject]
|
||||
}
|
||||
|
||||
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
|
||||
if let str = data as? String {
|
||||
if let num = str["~~(\\d)"].groups() {
|
||||
return binary[num[1].toInt()!]
|
||||
} else {
|
||||
return str
|
||||
}
|
||||
} else if let dict = data as? NSDictionary {
|
||||
var newDict = NSMutableDictionary(dictionary: dict)
|
||||
|
||||
for (key, value) in dict {
|
||||
newDict[key as! NSCopying] = _fillInPlaceholders(value)
|
||||
}
|
||||
|
||||
return newDict
|
||||
} else if let arr = data as? NSArray {
|
||||
var newArr = NSMutableArray(array: arr)
|
||||
|
||||
for i in 0..<arr.count {
|
||||
newArr[i] = _fillInPlaceholders(arr[i])
|
||||
}
|
||||
|
||||
return newArr
|
||||
} else {
|
||||
return data
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,264 +0,0 @@
|
||||
//
|
||||
// SocketParser.swift
|
||||
// Socket.IO-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
|
||||
// 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
|
||||
|
||||
class SocketParser {
|
||||
private static let shredder = SocketParser.PacketShredder()
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// Translation of socket.io-client#decodeString
|
||||
static func parseString(str:String) -> SocketPacket? {
|
||||
let arr = Array(str)
|
||||
let type = String(arr[0])
|
||||
|
||||
if arr.count == 1 {
|
||||
return SocketPacket(type: SocketPacket.PacketType(str: type))
|
||||
}
|
||||
|
||||
var id = nil as Int?
|
||||
var nsp = ""
|
||||
var i = 0
|
||||
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] == "-" {
|
||||
placeholders = holders
|
||||
} else {
|
||||
NSLog("Error parsing \(str)")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if arr[i + 1] == "/" {
|
||||
while ++i < arr.count {
|
||||
let c = arr[i]
|
||||
|
||||
if c == "," {
|
||||
break
|
||||
}
|
||||
|
||||
nsp += String(c)
|
||||
}
|
||||
}
|
||||
|
||||
if i + 1 >= arr.count {
|
||||
return SocketPacket(type: SocketPacket.PacketType(str: type),
|
||||
nsp: nsp, placeholders: placeholders, id: id)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
id = c.toInt()
|
||||
}
|
||||
|
||||
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?
|
||||
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
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
|
||||
static func parseForEmit(packet:SocketPacket) {
|
||||
shredder.deconstructPacket(packet)
|
||||
}
|
||||
|
||||
// Parses messages recieved
|
||||
static func parseSocketMessage(stringMessage:String, socket:SocketIOClient) {
|
||||
if stringMessage == "" {
|
||||
return
|
||||
}
|
||||
|
||||
func checkNSP(nsp:String) -> Bool {
|
||||
return nsp == "" && socket.nsp != "/"
|
||||
}
|
||||
|
||||
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!)
|
||||
}
|
||||
}
|
||||
|
||||
static func parseBinaryData(data:NSData, socket:SocketIOClient) {
|
||||
if socket.waitingData.count == 0 {
|
||||
SocketLogger.err("Got data when not remaking packet", client: socket, altType: "SocketParser")
|
||||
return
|
||||
}
|
||||
|
||||
let shouldExecute = socket.waitingData[0].addData(data)
|
||||
|
||||
if !shouldExecute {
|
||||
return
|
||||
}
|
||||
|
||||
let packet = socket.waitingData.removeAtIndex(0)
|
||||
packet.fillInPlaceholders()
|
||||
|
||||
if !packet.justAck {
|
||||
socket.handleEvent(packet.getEvent(), data: packet.data,
|
||||
wantsAck: packet.id)
|
||||
} else {
|
||||
socket.handleAck(packet.id!, data: packet.data)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
//
|
||||
// SwiftRegex.swift
|
||||
// SwiftRegex
|
||||
//
|
||||
// Created by John Holdsworth on 26/06/2014.
|
||||
// Copyright (c) 2014 John Holdsworth.
|
||||
//
|
||||
// $Id: //depot/SwiftRegex/SwiftRegex.swift#37 $
|
||||
//
|
||||
// This code is in the public domain from:
|
||||
// https://github.com/johnno1962/SwiftRegex
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
var swiftRegexCache = [String: NSRegularExpression]()
|
||||
|
||||
public class SwiftRegex: NSObject, BooleanType {
|
||||
var target:String
|
||||
var regex: NSRegularExpression
|
||||
|
||||
init(target:String, pattern:String, options:NSRegularExpressionOptions = nil) {
|
||||
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) {
|
||||
swiftRegexCache[pattern] = regex
|
||||
self.regex = regex
|
||||
}
|
||||
else {
|
||||
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
|
||||
self.regex = NSRegularExpression()
|
||||
}
|
||||
}
|
||||
super.init()
|
||||
}
|
||||
|
||||
class func failure(message: String) {
|
||||
println("SwiftRegex: "+message)
|
||||
//assert(false,"SwiftRegex: failed")
|
||||
}
|
||||
|
||||
final var targetRange: NSRange {
|
||||
return NSRange(location: 0,length: count(target.utf16))
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
public func range(options: NSMatchingOptions = nil) -> NSRange {
|
||||
return regex.rangeOfFirstMatchInString(target as String, options: nil, range: targetRange)
|
||||
}
|
||||
|
||||
public func match(options: NSMatchingOptions = nil) -> String? {
|
||||
return substring(range(options: options))
|
||||
}
|
||||
|
||||
public func groups(options: NSMatchingOptions = nil) -> [String]? {
|
||||
return groupsForMatch(regex.firstMatchInString(target as String, options: options, 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 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
public subscript(groupno: Int) -> String? {
|
||||
get {
|
||||
return groups()?[groupno]
|
||||
}
|
||||
|
||||
set(newValue) {
|
||||
if newValue == nil {
|
||||
return
|
||||
}
|
||||
|
||||
for match in 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
|
||||
}
|
||||
}
|
||||
|
||||
public func ranges(options: NSMatchingOptions = nil) -> [NSRange] {
|
||||
return matchResults(options: options)!.map { $0.range }
|
||||
}
|
||||
|
||||
public func matches(options: NSMatchingOptions = nil) -> [String] {
|
||||
return matchResults(options: options)!.map( { self.substring($0.range)!})
|
||||
}
|
||||
|
||||
public func allGroups(options: NSMatchingOptions = nil) -> [[String]?] {
|
||||
return matchResults(options: options)!.map {self.groupsForMatch($0)}
|
||||
}
|
||||
|
||||
public func dictionary(options: NSMatchingOptions = nil) -> Dictionary<String,String> {
|
||||
var out = Dictionary<String,String>()
|
||||
for match in matchResults(options: options)! {
|
||||
out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))!
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String),
|
||||
options:NSMatchingOptions = nil) -> 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
|
||||
out.appendString( self.substring(NSRange(location:pos, length:matchRange.location-pos))!)
|
||||
out.appendString( substitution(match, stop) )
|
||||
pos = matchRange.location + matchRange.length
|
||||
}
|
||||
|
||||
out.appendString(substring(NSRange(location:pos, length:targetRange.length-pos))!)
|
||||
|
||||
return out as String
|
||||
}
|
||||
|
||||
public var boolValue: Bool {
|
||||
return doesMatch()
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
public 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)
|
||||
}
|
||||
}
|
||||
|
||||
public 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)
|
||||
}
|
||||
|
||||
public 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)
|
||||
}
|
||||
|
||||
public 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)
|
||||
}
|
||||
|
||||
public func ~= (left: SwiftRegex, right: ([String]?) -> String) -> String {
|
||||
return left.substituteMatches({match, stop -> String in
|
||||
return right(left.groupsForMatch(match))
|
||||
}, options: nil)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//
|
||||
// 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...) {
|
||||
guard ackNum != -1 else { return }
|
||||
|
||||
socket.emitAck(ackNum, withItems: items)
|
||||
}
|
||||
|
||||
public func with(items: [AnyObject]) {
|
||||
guard ackNum != -1 else { return }
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//
|
||||
// SocketClientSpec.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 1/3/16.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
protocol SocketClientSpec: class {
|
||||
var nsp: String { get set }
|
||||
var waitingData: [SocketPacket] { get set }
|
||||
|
||||
func didConnect()
|
||||
func didDisconnect(reason: String)
|
||||
func didError(reason: String)
|
||||
func handleAck(ack: Int, data: [AnyObject])
|
||||
func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool, withAck ack: Int)
|
||||
func joinNamespace(namespace: String)
|
||||
}
|
||||
|
||||
extension SocketClientSpec {
|
||||
func didError(reason: String) {
|
||||
DefaultSocketLogger.Logger.error("%@", type: "SocketIOClient", args: reason)
|
||||
|
||||
handleEvent("error", data: [reason], isInternalMessage: true, withAck: -1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,561 @@
|
||||
//
|
||||
// SocketEngine.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/3/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 SocketEngine: NSObject, SocketEnginePollable, SocketEngineWebsocket {
|
||||
public let emitQueue = dispatch_queue_create("com.socketio.engineEmitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
public let handleQueue = dispatch_queue_create("com.socketio.engineHandleQueue", DISPATCH_QUEUE_SERIAL)
|
||||
public let parseQueue = dispatch_queue_create("com.socketio.engineParseQueue", DISPATCH_QUEUE_SERIAL)
|
||||
|
||||
public var postWait = [String]()
|
||||
public var waitingForPoll = false
|
||||
public var waitingForPost = false
|
||||
|
||||
public private(set) var closed = false
|
||||
public private(set) var connected = false
|
||||
public private(set) var cookies: [NSHTTPCookie]?
|
||||
public private(set) var extraHeaders: [String: String]?
|
||||
public private(set) var fastUpgrade = false
|
||||
public private(set) var forcePolling = false
|
||||
public private(set) var forceWebsockets = false
|
||||
public private(set) var invalidated = false
|
||||
public private(set) var pingTimer: NSTimer?
|
||||
public private(set) var polling = true
|
||||
public private(set) var probing = false
|
||||
public private(set) var session: NSURLSession?
|
||||
public private(set) var sid = ""
|
||||
public private(set) var socketPath = "/engine.io"
|
||||
public private(set) var urlPolling = ""
|
||||
public private(set) var urlWebSocket = ""
|
||||
public private(set) var websocket = false
|
||||
public private(set) var ws: WebSocket?
|
||||
|
||||
public weak var client: SocketEngineClient?
|
||||
|
||||
private weak var sessionDelegate: NSURLSessionDelegate?
|
||||
|
||||
private typealias Probe = (msg: String, type: SocketEnginePacketType, data: [NSData])
|
||||
private typealias ProbeWaitQueue = [Probe]
|
||||
|
||||
private let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
|
||||
private let logType = "SocketEngine"
|
||||
private let url: String
|
||||
|
||||
private var connectParams: [String: AnyObject]?
|
||||
private var pingInterval: Double?
|
||||
private var pingTimeout = 0.0 {
|
||||
didSet {
|
||||
pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25))
|
||||
}
|
||||
}
|
||||
private var pongsMissed = 0
|
||||
private var pongsMissedMax = 0
|
||||
private var probeWait = ProbeWaitQueue()
|
||||
private var secure = false
|
||||
private var selfSigned = false
|
||||
private var voipEnabled = false
|
||||
|
||||
public init(client: SocketEngineClient, url: String, options: Set<SocketIOClientOption>) {
|
||||
self.client = client
|
||||
self.url = url
|
||||
|
||||
for option in options {
|
||||
switch option {
|
||||
case let .SessionDelegate(delegate):
|
||||
sessionDelegate = delegate
|
||||
case let .ForcePolling(force):
|
||||
forcePolling = force
|
||||
case let .ForceWebsockets(force):
|
||||
forceWebsockets = force
|
||||
case let .Cookies(cookies):
|
||||
self.cookies = cookies
|
||||
case let .Path(path):
|
||||
socketPath = path
|
||||
case let .ExtraHeaders(headers):
|
||||
extraHeaders = headers
|
||||
case let .VoipEnabled(enable):
|
||||
voipEnabled = enable
|
||||
case let .Secure(secure):
|
||||
self.secure = secure
|
||||
case let .SelfSigned(selfSigned):
|
||||
self.selfSigned = selfSigned
|
||||
default:
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public convenience init(client: SocketEngineClient, url: String, options: NSDictionary?) {
|
||||
self.init(client: client, url: url,
|
||||
options: options?.toSocketOptionsSet() ?? [])
|
||||
}
|
||||
|
||||
deinit {
|
||||
DefaultSocketLogger.Logger.log("Engine is being deinit", type: logType)
|
||||
closed = true
|
||||
stopPolling()
|
||||
}
|
||||
|
||||
private func checkAndHandleEngineError(msg: String) {
|
||||
guard let stringData = msg.dataUsingEncoding(NSUTF8StringEncoding,
|
||||
allowLossyConversion: false) else { return }
|
||||
|
||||
do {
|
||||
if let dict = try NSJSONSerialization.JSONObjectWithData(stringData,
|
||||
options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
|
||||
guard let code = dict["code"] as? Int else { return }
|
||||
guard let error = dict["message"] as? String else { return }
|
||||
|
||||
switch code {
|
||||
case 0: // Unknown transport
|
||||
didError(error)
|
||||
case 1: // Unknown sid. clear and retry connect
|
||||
didError(error)
|
||||
case 2: // Bad handshake request
|
||||
didError(error)
|
||||
case 3: // Bad request
|
||||
didError(error)
|
||||
default:
|
||||
didError(error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
didError("Got unknown error from server \(msg)")
|
||||
}
|
||||
}
|
||||
|
||||
private func checkIfMessageIsBase64Binary(message: String) -> Bool {
|
||||
if message.hasPrefix("b4") {
|
||||
// binary in base64 string
|
||||
let noPrefix = message[message.startIndex.advancedBy(2)..<message.endIndex]
|
||||
|
||||
if let data = NSData(base64EncodedString: noPrefix,
|
||||
options: .IgnoreUnknownCharacters) {
|
||||
client?.parseEngineBinaryData(data)
|
||||
}
|
||||
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
public func close(reason: String) {
|
||||
func postSendClose(data: NSData?, _ res: NSURLResponse?, _ err: NSError?) {
|
||||
sid = ""
|
||||
closed = true
|
||||
invalidated = true
|
||||
connected = false
|
||||
|
||||
pingTimer?.invalidate()
|
||||
ws?.disconnect()
|
||||
stopPolling()
|
||||
client?.engineDidClose(reason)
|
||||
}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
|
||||
|
||||
if websocket {
|
||||
sendWebSocketMessage("", withType: .Close, withData: [])
|
||||
postSendClose(nil, nil, nil)
|
||||
} else {
|
||||
// We need to take special care when we're polling that we send it ASAP
|
||||
postWait.append(String(SocketEnginePacketType.Close.rawValue))
|
||||
let req = createRequestForPostWithPostWait()
|
||||
doRequest(req, withCallback: postSendClose)
|
||||
}
|
||||
}
|
||||
|
||||
private func createURLs(params: [String: AnyObject]?) -> (String, String) {
|
||||
if client == nil {
|
||||
return ("", "")
|
||||
}
|
||||
|
||||
let socketURL = "\(url)\(socketPath)/?transport="
|
||||
var urlPolling: String
|
||||
var urlWebSocket: String
|
||||
|
||||
if secure {
|
||||
urlPolling = "https://" + socketURL + "polling"
|
||||
urlWebSocket = "wss://" + socketURL + "websocket"
|
||||
} else {
|
||||
urlPolling = "http://" + socketURL + "polling"
|
||||
urlWebSocket = "ws://" + socketURL + "websocket"
|
||||
}
|
||||
|
||||
if params != nil {
|
||||
for (key, value) in params! {
|
||||
let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters(
|
||||
allowedCharacterSet)!
|
||||
urlPolling += "&\(keyEsc)="
|
||||
urlWebSocket += "&\(keyEsc)="
|
||||
|
||||
if value is String {
|
||||
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
|
||||
allowedCharacterSet)!
|
||||
urlPolling += "\(valueEsc)"
|
||||
urlWebSocket += "\(valueEsc)"
|
||||
} else {
|
||||
urlPolling += "\(value)"
|
||||
urlWebSocket += "\(value)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (urlPolling, urlWebSocket)
|
||||
}
|
||||
|
||||
private func createWebsocketAndConnect() {
|
||||
let wsUrl = urlWebSocket + (sid == "" ? "" : "&sid=\(sid)")
|
||||
|
||||
ws = WebSocket(url: NSURL(string: wsUrl)!)
|
||||
|
||||
if cookies != nil {
|
||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
|
||||
for (key, value) in headers {
|
||||
ws?.headers[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
if extraHeaders != nil {
|
||||
for (headerName, value) in extraHeaders! {
|
||||
ws?.headers[headerName] = value
|
||||
}
|
||||
}
|
||||
|
||||
ws?.queue = handleQueue
|
||||
ws?.voipEnabled = voipEnabled
|
||||
ws?.delegate = self
|
||||
ws?.selfSignedSSL = selfSigned
|
||||
|
||||
ws?.connect()
|
||||
}
|
||||
|
||||
public func didError(error: String) {
|
||||
DefaultSocketLogger.Logger.error(error, type: logType)
|
||||
client?.engineDidError(error)
|
||||
close(error)
|
||||
}
|
||||
|
||||
public func doFastUpgrade() {
|
||||
if waitingForPoll {
|
||||
DefaultSocketLogger.Logger.error("Outstanding poll when switched to WebSockets," +
|
||||
"we'll probably disconnect soon. You should report this.", type: logType)
|
||||
}
|
||||
|
||||
sendWebSocketMessage("", withType: .Upgrade, withData: [])
|
||||
websocket = true
|
||||
polling = false
|
||||
fastUpgrade = false
|
||||
probing = false
|
||||
flushProbeWait()
|
||||
}
|
||||
|
||||
private func flushProbeWait() {
|
||||
DefaultSocketLogger.Logger.log("Flushing probe wait", type: logType)
|
||||
|
||||
dispatch_async(emitQueue) {
|
||||
for waiter in self.probeWait {
|
||||
self.write(waiter.msg, withType: waiter.type, withData: waiter.data)
|
||||
}
|
||||
|
||||
self.probeWait.removeAll(keepCapacity: false)
|
||||
|
||||
if self.postWait.count != 0 {
|
||||
self.flushWaitingForPostToWebSocket()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We had packets waiting for send when we upgraded
|
||||
// Send them raw
|
||||
public func flushWaitingForPostToWebSocket() {
|
||||
guard let ws = self.ws else { return }
|
||||
|
||||
for msg in postWait {
|
||||
ws.writeString(fixDoubleUTF8(msg))
|
||||
}
|
||||
|
||||
postWait.removeAll(keepCapacity: true)
|
||||
}
|
||||
|
||||
private func handleClose(reason: String) {
|
||||
client?.engineDidClose(reason)
|
||||
}
|
||||
|
||||
private func handleMessage(message: String) {
|
||||
client?.parseEngineMessage(message)
|
||||
}
|
||||
|
||||
private func handleNOOP() {
|
||||
doPoll()
|
||||
}
|
||||
|
||||
private func handleOpen(openData: String) {
|
||||
let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
|
||||
do {
|
||||
let json = try NSJSONSerialization.JSONObjectWithData(mesData,
|
||||
options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
|
||||
if let sid = json?["sid"] as? String {
|
||||
let upgradeWs: Bool
|
||||
|
||||
self.sid = sid
|
||||
connected = true
|
||||
|
||||
if let upgrades = json?["upgrades"] as? [String] {
|
||||
upgradeWs = upgrades.contains("websocket")
|
||||
} else {
|
||||
upgradeWs = false
|
||||
}
|
||||
|
||||
if let pingInterval = json?["pingInterval"] as? Double, pingTimeout = json?["pingTimeout"] as? Double {
|
||||
self.pingInterval = pingInterval / 1000.0
|
||||
self.pingTimeout = pingTimeout / 1000.0
|
||||
}
|
||||
|
||||
if !forcePolling && !forceWebsockets && upgradeWs {
|
||||
createWebsocketAndConnect()
|
||||
}
|
||||
|
||||
|
||||
startPingTimer()
|
||||
|
||||
if !forceWebsockets {
|
||||
doPoll()
|
||||
}
|
||||
|
||||
client?.engineDidOpen?("Connect")
|
||||
}
|
||||
} catch {
|
||||
didError("Error parsing open packet")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
private func handlePong(pongMessage: String) {
|
||||
pongsMissed = 0
|
||||
|
||||
// We should upgrade
|
||||
if pongMessage == "3probe" {
|
||||
upgradeTransport()
|
||||
}
|
||||
}
|
||||
|
||||
public func open(opts: [String: AnyObject]?) {
|
||||
if connected {
|
||||
DefaultSocketLogger.Logger.error("Engine tried opening while connected. This is probably a programming error. "
|
||||
+ "Abandoning open attempt", type: logType)
|
||||
return
|
||||
}
|
||||
|
||||
connectParams = opts
|
||||
|
||||
DefaultSocketLogger.Logger.log("Starting engine", type: logType)
|
||||
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
|
||||
|
||||
resetEngine()
|
||||
|
||||
(urlPolling, urlWebSocket) = createURLs(opts)
|
||||
|
||||
if forceWebsockets {
|
||||
polling = false
|
||||
websocket = true
|
||||
createWebsocketAndConnect()
|
||||
return
|
||||
}
|
||||
|
||||
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
|
||||
|
||||
if cookies != nil {
|
||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
|
||||
reqPolling.allHTTPHeaderFields = headers
|
||||
}
|
||||
|
||||
if let extraHeaders = extraHeaders {
|
||||
for (headerName, value) in extraHeaders {
|
||||
reqPolling.setValue(value, forHTTPHeaderField: headerName)
|
||||
}
|
||||
}
|
||||
|
||||
doLongPoll(reqPolling)
|
||||
}
|
||||
|
||||
public func parseEngineData(data: NSData) {
|
||||
DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data)
|
||||
client?.parseEngineBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
|
||||
}
|
||||
|
||||
public func parseEngineMessage(message: String, fromPolling: Bool) {
|
||||
DefaultSocketLogger.Logger.log("Got message: %@", type: logType, args: message)
|
||||
|
||||
let reader = SocketStringReader(message: message)
|
||||
let fixedString: String
|
||||
|
||||
guard let type = SocketEnginePacketType(rawValue: Int(reader.currentCharacter) ?? -1) else {
|
||||
if !checkIfMessageIsBase64Binary(message) {
|
||||
checkAndHandleEngineError(message)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if fromPolling && type != .Noop {
|
||||
fixedString = fixDoubleUTF8(message)
|
||||
} else {
|
||||
fixedString = message
|
||||
}
|
||||
|
||||
switch type {
|
||||
case .Message:
|
||||
handleMessage(fixedString[fixedString.startIndex.successor()..<fixedString.endIndex])
|
||||
case .Noop:
|
||||
handleNOOP()
|
||||
case .Pong:
|
||||
handlePong(fixedString)
|
||||
case .Open:
|
||||
handleOpen(fixedString[fixedString.startIndex.successor()..<fixedString.endIndex])
|
||||
case .Close:
|
||||
handleClose(fixedString)
|
||||
default:
|
||||
DefaultSocketLogger.Logger.log("Got unknown packet type", type: logType)
|
||||
}
|
||||
}
|
||||
|
||||
private func resetEngine() {
|
||||
closed = false
|
||||
connected = false
|
||||
fastUpgrade = false
|
||||
polling = true
|
||||
probing = false
|
||||
invalidated = false
|
||||
session = NSURLSession(configuration: .defaultSessionConfiguration(),
|
||||
delegate: sessionDelegate,
|
||||
delegateQueue: NSOperationQueue())
|
||||
sid = ""
|
||||
waitingForPoll = false
|
||||
waitingForPost = false
|
||||
websocket = false
|
||||
}
|
||||
|
||||
/// Send an engine message (4)
|
||||
public func send(msg: String, withData datas: [NSData]) {
|
||||
if probing {
|
||||
probeWait.append((msg, .Message, datas))
|
||||
} else {
|
||||
write(msg, withType: .Message, withData: datas)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func sendPing() {
|
||||
//Server is not responding
|
||||
if pongsMissed > pongsMissedMax {
|
||||
pingTimer?.invalidate()
|
||||
client?.engineDidClose("Ping timeout")
|
||||
return
|
||||
}
|
||||
|
||||
pongsMissed += 1
|
||||
write("", withType: .Ping, withData: [])
|
||||
}
|
||||
|
||||
// Starts the ping timer
|
||||
private func startPingTimer() {
|
||||
if let pingInterval = pingInterval {
|
||||
pingTimer?.invalidate()
|
||||
pingTimer = nil
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self,
|
||||
selector: Selector("sendPing"), userInfo: nil, repeats: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func upgradeTransport() {
|
||||
if ws?.isConnected ?? false {
|
||||
DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: logType)
|
||||
|
||||
fastUpgrade = true
|
||||
sendPollMessage("", withType: .Noop, withData: [])
|
||||
// After this point, we should not send anymore polling messages
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Write a message, independent of transport.
|
||||
*/
|
||||
public func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData]) {
|
||||
dispatch_async(emitQueue) {
|
||||
guard self.connected else { return }
|
||||
|
||||
if self.websocket {
|
||||
DefaultSocketLogger.Logger.log("Writing ws: %@ has data: %@",
|
||||
type: self.logType, args: msg, data.count != 0)
|
||||
self.sendWebSocketMessage(msg, withType: type, withData: data)
|
||||
} else {
|
||||
DefaultSocketLogger.Logger.log("Writing poll: %@ has data: %@",
|
||||
type: self.logType, args: msg, data.count != 0)
|
||||
self.sendPollMessage(msg, withType: type, withData: data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delegate methods
|
||||
public func websocketDidConnect(socket: WebSocket) {
|
||||
if !forceWebsockets {
|
||||
probing = true
|
||||
probeWebSocket()
|
||||
} else {
|
||||
connected = true
|
||||
probing = false
|
||||
polling = false
|
||||
}
|
||||
}
|
||||
|
||||
public func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
|
||||
probing = false
|
||||
|
||||
if closed {
|
||||
client?.engineDidClose("Disconnect")
|
||||
return
|
||||
}
|
||||
|
||||
if websocket {
|
||||
pingTimer?.invalidate()
|
||||
connected = false
|
||||
websocket = false
|
||||
|
||||
let reason = error?.localizedDescription ?? "Socket Disconnected"
|
||||
|
||||
if error != nil {
|
||||
didError(reason)
|
||||
}
|
||||
|
||||
client?.engineDidClose(reason)
|
||||
} else {
|
||||
flushProbeWait()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//
|
||||
// SocketEngineClient.swift
|
||||
// Socket.IO-Swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/19/15.
|
||||
//
|
||||
@@ -25,13 +25,10 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
@objc public protocol SocketEngineClient {
|
||||
var handleQueue:dispatch_queue_attr_t! {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)
|
||||
@objc public protocol SocketEngineClient {
|
||||
func engineDidError(reason: String)
|
||||
func engineDidClose(reason: String)
|
||||
optional func engineDidOpen(reason: String)
|
||||
func parseEngineMessage(msg: String)
|
||||
func parseEngineBinaryData(data: NSData)
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
//
|
||||
// SocketFixUTF8.swift
|
||||
// Socket.IO-Swift
|
||||
// SocketEnginePacketType.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/16/15.
|
||||
// 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
|
||||
@@ -25,14 +25,6 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
func fixDoubleUTF8(inout name:String) {
|
||||
let utf8 = name.dataUsingEncoding(NSISOLatin1StringEncoding)!
|
||||
let 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
|
||||
}
|
||||
@objc public enum SocketEnginePacketType: Int {
|
||||
case Open, Close, Ping, Pong, Message, Upgrade, Noop
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
//
|
||||
// SocketEnginePollable.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 1/15/16.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Protocol that is used to implement socket.io polling support
|
||||
public protocol SocketEnginePollable: SocketEngineSpec {
|
||||
var invalidated: Bool { get }
|
||||
/// Holds strings waiting to be sent over polling.
|
||||
/// You shouldn't need to mess with this.
|
||||
var postWait: [String] { get set }
|
||||
var session: NSURLSession? { get }
|
||||
/// Because socket.io doesn't let you send two polling request at the same time
|
||||
/// we have to keep track if there's an outstanding poll
|
||||
var waitingForPoll: Bool { get set }
|
||||
/// Because socket.io doesn't let you send two post request at the same time
|
||||
/// we have to keep track if there's an outstanding post
|
||||
var waitingForPost: Bool { get set }
|
||||
|
||||
func doPoll()
|
||||
func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData])
|
||||
func stopPolling()
|
||||
}
|
||||
|
||||
// Default polling methods
|
||||
extension SocketEnginePollable {
|
||||
private func addHeaders(req: NSMutableURLRequest) {
|
||||
if cookies != nil {
|
||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
|
||||
req.allHTTPHeaderFields = headers
|
||||
}
|
||||
|
||||
if extraHeaders != nil {
|
||||
for (headerName, value) in extraHeaders! {
|
||||
req.setValue(value, forHTTPHeaderField: headerName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func createRequestForPostWithPostWait() -> NSURLRequest {
|
||||
var postStr = ""
|
||||
|
||||
for packet in postWait {
|
||||
let len = packet.characters.count
|
||||
|
||||
postStr += "\(len):\(packet)"
|
||||
}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Created POST string: %@", type: "SocketEnginePolling", args: postStr)
|
||||
|
||||
postWait.removeAll(keepCapacity: false)
|
||||
|
||||
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&sid=\(sid)")!)
|
||||
|
||||
addHeaders(req)
|
||||
|
||||
req.HTTPMethod = "POST"
|
||||
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
|
||||
|
||||
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
|
||||
allowLossyConversion: false)!
|
||||
|
||||
req.HTTPBody = postData
|
||||
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
|
||||
|
||||
return req
|
||||
}
|
||||
|
||||
public func doPoll() {
|
||||
if websocket || waitingForPoll || !connected || closed {
|
||||
return
|
||||
}
|
||||
|
||||
waitingForPoll = true
|
||||
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&sid=\(sid)&b64=1")!)
|
||||
|
||||
addHeaders(req)
|
||||
doLongPoll(req)
|
||||
}
|
||||
|
||||
func doRequest(req: NSURLRequest, withCallback callback: (NSData?, NSURLResponse?, NSError?) -> Void) {
|
||||
if !polling || closed || invalidated {
|
||||
DefaultSocketLogger.Logger.error("Tried to do polling request when not supposed to", type: "SocketEnginePolling")
|
||||
return
|
||||
}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling")
|
||||
|
||||
session?.dataTaskWithRequest(req, completionHandler: callback).resume()
|
||||
}
|
||||
|
||||
func doLongPoll(req: NSURLRequest) {
|
||||
doRequest(req) {[weak self] data, res, err in
|
||||
guard let this = self else {return}
|
||||
|
||||
if err != nil || data == nil {
|
||||
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
|
||||
|
||||
if this.polling {
|
||||
this.didError(err?.localizedDescription ?? "Error")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Got polling response", type: "SocketEnginePolling")
|
||||
|
||||
if let str = String(data: data!, encoding: NSUTF8StringEncoding) {
|
||||
dispatch_async(this.parseQueue) {
|
||||
this.parsePollingMessage(str)
|
||||
}
|
||||
}
|
||||
|
||||
this.waitingForPoll = false
|
||||
|
||||
if this.fastUpgrade {
|
||||
this.doFastUpgrade()
|
||||
} else if !this.closed && this.polling {
|
||||
this.doPoll()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func flushWaitingForPost() {
|
||||
if postWait.count == 0 || !connected {
|
||||
return
|
||||
} else if websocket {
|
||||
flushWaitingForPostToWebSocket()
|
||||
return
|
||||
}
|
||||
|
||||
let req = createRequestForPostWithPostWait()
|
||||
|
||||
waitingForPost = true
|
||||
|
||||
DefaultSocketLogger.Logger.log("POSTing", type: "SocketEnginePolling")
|
||||
|
||||
doRequest(req) {[weak self] data, res, err in
|
||||
guard let this = self else { return }
|
||||
|
||||
if err != nil {
|
||||
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
|
||||
|
||||
if this.polling {
|
||||
this.didError(err?.localizedDescription ?? "Error")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
this.waitingForPost = false
|
||||
|
||||
dispatch_async(this.emitQueue) {
|
||||
if !this.fastUpgrade {
|
||||
this.flushWaitingForPost()
|
||||
this.doPoll()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parsePollingMessage(str: String) {
|
||||
guard str.characters.count != 1 else {
|
||||
return
|
||||
}
|
||||
|
||||
var reader = SocketStringReader(message: str)
|
||||
|
||||
while reader.hasNext {
|
||||
if let n = Int(reader.readUntilStringOccurence(":")) {
|
||||
let str = reader.read(n)
|
||||
|
||||
dispatch_async(handleQueue) {
|
||||
self.parseEngineMessage(str, fromPolling: true)
|
||||
}
|
||||
} else {
|
||||
dispatch_async(handleQueue) {
|
||||
self.parseEngineMessage(str, fromPolling: true)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Send polling message.
|
||||
/// Only call on emitQueue
|
||||
public func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData]) {
|
||||
DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue)
|
||||
let fixedMessage = doubleEncodeUTF8(message)
|
||||
let strMsg = "\(type.rawValue)\(fixedMessage)"
|
||||
|
||||
postWait.append(strMsg)
|
||||
|
||||
for data in datas {
|
||||
if case let .Right(bin) = createBinaryDataForSend(data) {
|
||||
postWait.append(bin)
|
||||
}
|
||||
}
|
||||
|
||||
if !waitingForPost {
|
||||
flushWaitingForPost()
|
||||
}
|
||||
}
|
||||
|
||||
public func stopPolling() {
|
||||
waitingForPoll = false
|
||||
waitingForPost = false
|
||||
session?.finishTasksAndInvalidate()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//
|
||||
// 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 closed: Bool { get }
|
||||
var connected: Bool { get }
|
||||
var cookies: [NSHTTPCookie]? { get }
|
||||
var extraHeaders: [String: String]? { get }
|
||||
var fastUpgrade: Bool { get }
|
||||
var forcePolling: Bool { get }
|
||||
var forceWebsockets: Bool { get }
|
||||
var parseQueue: dispatch_queue_t! { get }
|
||||
var pingTimer: NSTimer? { get }
|
||||
var polling: Bool { get }
|
||||
var probing: Bool { get }
|
||||
var emitQueue: dispatch_queue_t! { get }
|
||||
var handleQueue: dispatch_queue_t! { get }
|
||||
var sid: String { get }
|
||||
var socketPath: String { get }
|
||||
var urlPolling: String { get }
|
||||
var urlWebSocket: String { get }
|
||||
var websocket: Bool { get }
|
||||
|
||||
init(client: SocketEngineClient, url: String, options: NSDictionary?)
|
||||
|
||||
func close(reason: String)
|
||||
func didError(error: String)
|
||||
func doFastUpgrade()
|
||||
func flushWaitingForPostToWebSocket()
|
||||
func open(opts: [String: AnyObject]?)
|
||||
func parseEngineData(data: NSData)
|
||||
func parseEngineMessage(message: String, fromPolling: Bool)
|
||||
func send(msg: String, withData datas: [NSData])
|
||||
func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData])
|
||||
}
|
||||
|
||||
extension SocketEngineSpec {
|
||||
func createBinaryDataForSend(data: NSData) -> Either<NSData, String> {
|
||||
if websocket {
|
||||
var byteArray = [UInt8](count: 1, repeatedValue: 0x4)
|
||||
let mutData = NSMutableData(bytes: &byteArray, length: 1)
|
||||
|
||||
mutData.appendData(data)
|
||||
|
||||
return .Left(mutData)
|
||||
} else {
|
||||
let str = "b4" + data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
|
||||
|
||||
return .Right(str)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
//
|
||||
// SocketEngineWebsocket.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 1/15/16.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Protocol that is used to implement socket.io WebSocket support
|
||||
public protocol SocketEngineWebsocket: SocketEngineSpec, WebSocketDelegate {
|
||||
var ws: WebSocket? { get }
|
||||
|
||||
func sendWebSocketMessage(str: String, withType type: SocketEnginePacketType, withData datas: [NSData])
|
||||
}
|
||||
|
||||
// WebSocket methods
|
||||
extension SocketEngineWebsocket {
|
||||
func probeWebSocket() {
|
||||
if ws?.isConnected ?? false {
|
||||
sendWebSocketMessage("probe", withType: .Ping, withData: [])
|
||||
}
|
||||
}
|
||||
|
||||
/// Send message on WebSockets
|
||||
/// Only call on emitQueue
|
||||
public func sendWebSocketMessage(str: String, withType type: SocketEnginePacketType, withData datas: [NSData]) {
|
||||
DefaultSocketLogger.Logger.log("Sending ws: %@ as type: %@", type: "SocketEngine", args: str, type.rawValue)
|
||||
|
||||
ws?.writeString("\(type.rawValue)\(str)")
|
||||
|
||||
for data in datas {
|
||||
if case let .Left(bin) = createBinaryDataForSend(data) {
|
||||
ws?.writeData(bin)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func websocketDidReceiveMessage(socket: WebSocket, text: String) {
|
||||
parseEngineMessage(text, fromPolling: false)
|
||||
}
|
||||
|
||||
public func websocketDidReceiveData(socket: WebSocket, data: NSData) {
|
||||
parseEngineData(data)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//
|
||||
// EventHandler.swift
|
||||
// Socket.IO-Swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 1/18/15.
|
||||
//
|
||||
@@ -24,22 +24,12 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
private func emitAckCallback(socket:SocketIOClient, num:Int)
|
||||
(items:AnyObject...) -> Void {
|
||||
socket.emitAck(num, withData: items)
|
||||
}
|
||||
|
||||
final class SocketEventHandler {
|
||||
let event:String!
|
||||
let callback:NormalCallback?
|
||||
struct SocketEventHandler {
|
||||
let event: String
|
||||
let id: NSUUID
|
||||
let callback: NormalCallback
|
||||
|
||||
init(event:String, callback:NormalCallback) {
|
||||
self.event = event
|
||||
self.callback = callback
|
||||
}
|
||||
|
||||
func executeCallback(_ items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
|
||||
withSocket socket:SocketIOClient? = nil) {
|
||||
self.callback?(items, ack != nil ? emitAckCallback(socket!, ack!) : nil)
|
||||
func executeCallback(items: [AnyObject], withAck ack: Int, withSocket socket: SocketIOClient) {
|
||||
callback(items, SocketAckEmitter(socket: socket, ackNum: ack))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//
|
||||
// SocketFixUTF8.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/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
|
||||
|
||||
func fixDoubleUTF8(string: String) -> String {
|
||||
if let utf8 = string.dataUsingEncoding(NSISOLatin1StringEncoding),
|
||||
latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding) {
|
||||
return latin1 as String
|
||||
} else {
|
||||
return string
|
||||
}
|
||||
}
|
||||
|
||||
func doubleEncodeUTF8(string: String) -> String {
|
||||
if let latin1 = string.dataUsingEncoding(NSUTF8StringEncoding),
|
||||
utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding) {
|
||||
return utf8 as String
|
||||
} else {
|
||||
return string
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,514 @@
|
||||
//
|
||||
// SocketIOClient.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 11/23/14.
|
||||
//
|
||||
// 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 SocketIOClient: NSObject, SocketEngineClient, SocketParsable {
|
||||
public let socketURL: String
|
||||
|
||||
public private(set) var engine: SocketEngineSpec?
|
||||
public private(set) var status = SocketIOClientStatus.NotConnected
|
||||
|
||||
public var connectParams: [String: AnyObject]?
|
||||
public var forceNew = false
|
||||
public var nsp = "/"
|
||||
public var options: Set<SocketIOClientOption>
|
||||
public var reconnects = true
|
||||
public var reconnectWait = 10
|
||||
public var sid: String? {
|
||||
return engine?.sid
|
||||
}
|
||||
|
||||
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let logType = "SocketIOClient"
|
||||
private let parseQueue = dispatch_queue_create("com.socketio.parseQueue", DISPATCH_QUEUE_SERIAL)
|
||||
|
||||
private var anyHandler: ((SocketAnyEvent) -> Void)?
|
||||
private var currentReconnectAttempt = 0
|
||||
private var handlers = [SocketEventHandler]()
|
||||
private var reconnectTimer: NSTimer?
|
||||
private var ackHandlers = SocketAckManager()
|
||||
|
||||
private(set) var currentAck = -1
|
||||
private(set) var handleQueue = dispatch_get_main_queue()
|
||||
private(set) var reconnectAttempts = -1
|
||||
|
||||
var waitingData = [SocketPacket]()
|
||||
|
||||
/**
|
||||
Type safe way to create a new SocketIOClient. opts can be omitted
|
||||
*/
|
||||
public init(socketURL: String, options: Set<SocketIOClientOption> = []) {
|
||||
self.options = options
|
||||
|
||||
if socketURL["https://"].matches().count != 0 {
|
||||
self.options.insertIgnore(.Secure(true))
|
||||
}
|
||||
|
||||
self.socketURL = socketURL["https?://"] <~ ""
|
||||
|
||||
for option in options {
|
||||
switch option {
|
||||
case let .ConnectParams(params):
|
||||
connectParams = params
|
||||
case let .Reconnects(reconnects):
|
||||
self.reconnects = reconnects
|
||||
case let .ReconnectAttempts(attempts):
|
||||
reconnectAttempts = attempts
|
||||
case let .ReconnectWait(wait):
|
||||
reconnectWait = abs(wait)
|
||||
case let .Nsp(nsp):
|
||||
self.nsp = nsp
|
||||
case let .Log(log):
|
||||
DefaultSocketLogger.Logger.log = log
|
||||
case let .Logger(logger):
|
||||
DefaultSocketLogger.Logger = logger
|
||||
case let .HandleQueue(queue):
|
||||
handleQueue = queue
|
||||
case let .ForceNew(force):
|
||||
forceNew = force
|
||||
default:
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
self.options.insertIgnore(.Path("/socket.io"))
|
||||
|
||||
super.init()
|
||||
}
|
||||
|
||||
/**
|
||||
Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity.
|
||||
If using Swift it's recommended to use `init(var socketURL: String, options: Set<SocketIOClientOption>)`
|
||||
*/
|
||||
public convenience init(socketURL: String, options: NSDictionary?) {
|
||||
self.init(socketURL: socketURL,
|
||||
options: options?.toSocketOptionsSet() ?? [])
|
||||
}
|
||||
|
||||
deinit {
|
||||
DefaultSocketLogger.Logger.log("Client is being deinit", type: logType)
|
||||
engine?.close("Client Deinit")
|
||||
}
|
||||
|
||||
private func addEngine() -> SocketEngineSpec {
|
||||
DefaultSocketLogger.Logger.log("Adding engine", type: logType)
|
||||
|
||||
engine = SocketEngine(client: self, url: socketURL, options: options)
|
||||
|
||||
return engine!
|
||||
}
|
||||
|
||||
private func clearReconnectTimer() {
|
||||
reconnectTimer?.invalidate()
|
||||
reconnectTimer = nil
|
||||
}
|
||||
|
||||
@available(*, deprecated=6.0)
|
||||
public func close() {
|
||||
disconnect()
|
||||
}
|
||||
|
||||
/**
|
||||
Connect to the server.
|
||||
*/
|
||||
public func connect() {
|
||||
connect(timeoutAfter: 0, withTimeoutHandler: nil)
|
||||
}
|
||||
|
||||
/**
|
||||
Connect to the server. If we aren't connected after timeoutAfter, call handler
|
||||
*/
|
||||
public func connect(timeoutAfter timeoutAfter: Int, withTimeoutHandler handler: (() -> Void)?) {
|
||||
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
|
||||
|
||||
guard status != .Connected else {
|
||||
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket",
|
||||
type: logType)
|
||||
return
|
||||
}
|
||||
|
||||
status = .Connecting
|
||||
|
||||
if engine == nil || forceNew {
|
||||
addEngine().open(connectParams)
|
||||
} else {
|
||||
engine?.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("Connect timeout")
|
||||
|
||||
handler?()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func createOnAck(items: [AnyObject]) -> OnAckCallback {
|
||||
currentAck += 1
|
||||
|
||||
return {[weak self, ack = currentAck] timeout, callback in
|
||||
if let this = self {
|
||||
this.ackHandlers.addAck(ack, callback: callback)
|
||||
|
||||
dispatch_async(this.emitQueue) {
|
||||
this._emit(items, ack: ack)
|
||||
}
|
||||
|
||||
if timeout != 0 {
|
||||
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
|
||||
|
||||
dispatch_after(time, this.handleQueue) {
|
||||
this.ackHandlers.timeoutAck(ack)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func didConnect() {
|
||||
DefaultSocketLogger.Logger.log("Socket connected", type: logType)
|
||||
status = .Connected
|
||||
currentReconnectAttempt = 0
|
||||
clearReconnectTimer()
|
||||
|
||||
// Don't handle as internal because something crazy could happen where
|
||||
// we disconnect before it's handled
|
||||
handleEvent("connect", data: [], isInternalMessage: false)
|
||||
}
|
||||
|
||||
func didDisconnect(reason: String) {
|
||||
guard status != .Closed else {
|
||||
return
|
||||
}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason)
|
||||
|
||||
status = .Closed
|
||||
reconnects = false
|
||||
|
||||
// Make sure the engine is actually dead.
|
||||
engine?.close(reason)
|
||||
handleEvent("disconnect", data: [reason], isInternalMessage: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Disconnects the socket. Only reconnect the same socket if you know what you're doing.
|
||||
Will turn off automatic reconnects.
|
||||
*/
|
||||
public func disconnect() {
|
||||
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
|
||||
|
||||
reconnects = false
|
||||
didDisconnect("Disconnect")
|
||||
}
|
||||
|
||||
/**
|
||||
Send a message to the server
|
||||
*/
|
||||
public func emit(event: String, _ items: AnyObject...) {
|
||||
emit(event, withItems: items)
|
||||
}
|
||||
|
||||
/**
|
||||
Same as emit, but meant for Objective-C
|
||||
*/
|
||||
public func emit(event: String, withItems items: [AnyObject]) {
|
||||
guard status == .Connected else {
|
||||
handleEvent("error", data: ["Tried emitting \(event) when not connected"], isInternalMessage: true)
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(emitQueue) {
|
||||
self._emit([event] + items)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
|
||||
an ack.
|
||||
*/
|
||||
public func emitWithAck(event: String, _ items: AnyObject...) -> OnAckCallback {
|
||||
return emitWithAck(event, withItems: items)
|
||||
}
|
||||
|
||||
/**
|
||||
Same as emitWithAck, but for Objective-C
|
||||
*/
|
||||
public func emitWithAck(event: String, withItems items: [AnyObject]) -> OnAckCallback {
|
||||
return createOnAck([event] + items)
|
||||
}
|
||||
|
||||
private func _emit(data: [AnyObject], ack: Int? = nil) {
|
||||
guard status == .Connected else {
|
||||
handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
|
||||
return
|
||||
}
|
||||
|
||||
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
|
||||
let str = packet.packetString
|
||||
|
||||
DefaultSocketLogger.Logger.log("Emitting: %@", type: logType, args: str)
|
||||
|
||||
engine?.send(str, withData: packet.binary)
|
||||
}
|
||||
|
||||
// If the server wants to know that the client received data
|
||||
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
|
||||
|
||||
DefaultSocketLogger.Logger.log("Emitting Ack: %@", type: self.logType, args: str)
|
||||
|
||||
self.engine?.send(str, withData: packet.binary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func engineDidClose(reason: String) {
|
||||
waitingData.removeAll()
|
||||
|
||||
if status == .Closed || !reconnects {
|
||||
didDisconnect(reason)
|
||||
} else if status != .Reconnecting {
|
||||
status = .Reconnecting
|
||||
handleEvent("reconnect", data: [reason], isInternalMessage: true)
|
||||
tryReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
/// error
|
||||
public func engineDidError(reason: String) {
|
||||
DefaultSocketLogger.Logger.error("%@", type: logType, args: reason)
|
||||
|
||||
handleEvent("error", data: [reason], isInternalMessage: true)
|
||||
}
|
||||
|
||||
// Called when the socket gets an ack for something it sent
|
||||
func handleAck(ack: Int, data: [AnyObject]) {
|
||||
guard status == .Connected else {return}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
|
||||
|
||||
ackHandlers.executeAck(ack, items: data)
|
||||
}
|
||||
|
||||
/**
|
||||
Causes an event to be handled. Only use if you know what you're doing.
|
||||
*/
|
||||
public func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool, withAck ack: Int = -1) {
|
||||
guard status == .Connected || isInternalMessage else {
|
||||
return
|
||||
}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data ?? "")
|
||||
|
||||
dispatch_async(handleQueue) {
|
||||
self.anyHandler?(SocketAnyEvent(event: event, items: data))
|
||||
|
||||
for handler in self.handlers where handler.event == event {
|
||||
handler.executeCallback(data, withAck: ack, withSocket: self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Leaves nsp and goes back to /
|
||||
*/
|
||||
public func leaveNamespace() {
|
||||
if nsp != "/" {
|
||||
engine?.send("1\(nsp)", withData: [])
|
||||
nsp = "/"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Joins namespace
|
||||
*/
|
||||
public func joinNamespace(namespace: String) {
|
||||
nsp = namespace
|
||||
|
||||
if nsp != "/" {
|
||||
DefaultSocketLogger.Logger.log("Joining namespace", type: logType)
|
||||
engine?.send("0\(nsp)", withData: [])
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Removes handler(s)
|
||||
*/
|
||||
public func off(event: String) {
|
||||
DefaultSocketLogger.Logger.log("Removing handler for event: %@", type: logType, args: event)
|
||||
|
||||
handlers = handlers.filter { $0.event != event }
|
||||
}
|
||||
|
||||
/**
|
||||
Removes a handler with the specified UUID gotten from an `on` or `once`
|
||||
*/
|
||||
public func off(id id: NSUUID) {
|
||||
DefaultSocketLogger.Logger.log("Removing handler with id: %@", type: logType, args: id)
|
||||
|
||||
handlers = handlers.filter { $0.id != id }
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler for an event.
|
||||
Returns: A unique id for the handler
|
||||
*/
|
||||
public func on(event: String, callback: NormalCallback) -> NSUUID {
|
||||
DefaultSocketLogger.Logger.log("Adding handler for event: %@", type: logType, args: event)
|
||||
|
||||
let handler = SocketEventHandler(event: event, id: NSUUID(), callback: callback)
|
||||
handlers.append(handler)
|
||||
|
||||
return handler.id
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a single-use handler for an event.
|
||||
Returns: A unique id for the handler
|
||||
*/
|
||||
public func once(event: String, callback: NormalCallback) -> NSUUID {
|
||||
DefaultSocketLogger.Logger.log("Adding once handler for event: %@", type: logType, args: event)
|
||||
|
||||
let id = NSUUID()
|
||||
|
||||
let handler = SocketEventHandler(event: event, id: id) {[weak self] data, ack in
|
||||
guard let this = self else {return}
|
||||
this.off(id: id)
|
||||
callback(data, ack)
|
||||
}
|
||||
|
||||
handlers.append(handler)
|
||||
|
||||
return handler.id
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler that will be called on every event.
|
||||
*/
|
||||
public func onAny(handler: (SocketAnyEvent) -> Void) {
|
||||
anyHandler = handler
|
||||
}
|
||||
|
||||
/**
|
||||
Same as connect
|
||||
*/
|
||||
@available(*, deprecated=6.0)
|
||||
public func open() {
|
||||
connect()
|
||||
}
|
||||
|
||||
public func parseEngineMessage(msg: String) {
|
||||
DefaultSocketLogger.Logger.log("Should parse message: %@", type: "SocketIOClient", args: msg)
|
||||
|
||||
dispatch_async(parseQueue) {
|
||||
self.parseSocketMessage(msg)
|
||||
}
|
||||
}
|
||||
|
||||
public func parseEngineBinaryData(data: NSData) {
|
||||
dispatch_async(parseQueue) {
|
||||
self.parseBinaryData(data)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tries to reconnect to the server.
|
||||
*/
|
||||
public func reconnect() {
|
||||
tryReconnect()
|
||||
}
|
||||
|
||||
/**
|
||||
Removes all handlers.
|
||||
Can be used after disconnecting to break any potential remaining retain cycles.
|
||||
*/
|
||||
public func removeAllHandlers() {
|
||||
handlers.removeAll(keepCapacity: false)
|
||||
}
|
||||
|
||||
private func tryReconnect() {
|
||||
if reconnectTimer == nil {
|
||||
DefaultSocketLogger.Logger.log("Starting reconnect", type: logType)
|
||||
|
||||
status = .Reconnecting
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
self.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self.reconnectWait),
|
||||
target: self, selector: "_tryReconnect", userInfo: nil, repeats: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func _tryReconnect() {
|
||||
if status == .Connected {
|
||||
clearReconnectTimer()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
|
||||
clearReconnectTimer()
|
||||
didDisconnect("Reconnect Failed")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType)
|
||||
handleEvent("reconnectAttempt", data: [reconnectAttempts - currentReconnectAttempt],
|
||||
isInternalMessage: true)
|
||||
|
||||
currentReconnectAttempt += 1
|
||||
connect()
|
||||
}
|
||||
}
|
||||
|
||||
// Test extensions
|
||||
extension SocketIOClient {
|
||||
var testHandlers: [SocketEventHandler] {
|
||||
return handlers
|
||||
}
|
||||
|
||||
func setTestable() {
|
||||
status = .Connected
|
||||
}
|
||||
|
||||
func setTestEngine(engine: SocketEngineSpec?) {
|
||||
self.engine = engine
|
||||
}
|
||||
|
||||
func emitTest(event: String, _ data: AnyObject...) {
|
||||
self._emit([event] + data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
//
|
||||
// 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
|
||||
|
||||
protocol ClientOption: CustomStringConvertible, Hashable {
|
||||
func getSocketIOOptionValue() -> AnyObject
|
||||
}
|
||||
|
||||
public enum SocketIOClientOption: ClientOption {
|
||||
case ConnectParams([String: AnyObject])
|
||||
case Cookies([NSHTTPCookie])
|
||||
case ExtraHeaders([String: String])
|
||||
case ForceNew(Bool)
|
||||
case ForcePolling(Bool)
|
||||
case ForceWebsockets(Bool)
|
||||
case HandleQueue(dispatch_queue_t)
|
||||
case Log(Bool)
|
||||
case Logger(SocketLogger)
|
||||
case Nsp(String)
|
||||
case Path(String)
|
||||
case Reconnects(Bool)
|
||||
case ReconnectAttempts(Int)
|
||||
case ReconnectWait(Int)
|
||||
case Secure(Bool)
|
||||
case SelfSigned(Bool)
|
||||
case SessionDelegate(NSURLSessionDelegate)
|
||||
case VoipEnabled(Bool)
|
||||
|
||||
public var description: String {
|
||||
let description: String
|
||||
|
||||
switch self {
|
||||
case .ConnectParams:
|
||||
description = "connectParams"
|
||||
case .Cookies:
|
||||
description = "cookies"
|
||||
case .ExtraHeaders:
|
||||
description = "extraHeaders"
|
||||
case .ForceNew:
|
||||
description = "forceNew"
|
||||
case .ForcePolling:
|
||||
description = "forcePolling"
|
||||
case .ForceWebsockets:
|
||||
description = "forceWebsockets"
|
||||
case .HandleQueue:
|
||||
description = "handleQueue"
|
||||
case .Log:
|
||||
description = "log"
|
||||
case .Logger:
|
||||
description = "logger"
|
||||
case .Nsp:
|
||||
description = "nsp"
|
||||
case .Path:
|
||||
description = "path"
|
||||
case .Reconnects:
|
||||
description = "reconnects"
|
||||
case .ReconnectAttempts:
|
||||
description = "reconnectAttempts"
|
||||
case .ReconnectWait:
|
||||
description = "reconnectWait"
|
||||
case .Secure:
|
||||
description = "secure"
|
||||
case .SelfSigned:
|
||||
description = "selfSigned"
|
||||
case .SessionDelegate:
|
||||
description = "sessionDelegate"
|
||||
case .VoipEnabled:
|
||||
description = "voipEnabled"
|
||||
}
|
||||
|
||||
return description
|
||||
}
|
||||
|
||||
public var hashValue: Int {
|
||||
return description.hashValue
|
||||
}
|
||||
|
||||
func getSocketIOOptionValue() -> AnyObject {
|
||||
let value: AnyObject
|
||||
|
||||
switch self {
|
||||
case let .ConnectParams(params):
|
||||
value = params
|
||||
case let .Cookies(cookies):
|
||||
value = cookies
|
||||
case let .ExtraHeaders(headers):
|
||||
value = headers
|
||||
case let .ForceNew(force):
|
||||
value = force
|
||||
case let .ForcePolling(force):
|
||||
value = force
|
||||
case let .ForceWebsockets(force):
|
||||
value = force
|
||||
case let .HandleQueue(queue):
|
||||
value = queue
|
||||
case let .Log(log):
|
||||
value = log
|
||||
case let .Logger(logger):
|
||||
value = logger
|
||||
case let .Nsp(nsp):
|
||||
value = nsp
|
||||
case let .Path(path):
|
||||
value = path
|
||||
case let .Reconnects(reconnects):
|
||||
value = reconnects
|
||||
case let .ReconnectAttempts(attempts):
|
||||
value = attempts
|
||||
case let .ReconnectWait(wait):
|
||||
value = wait
|
||||
case let .Secure(secure):
|
||||
value = secure
|
||||
case let .SelfSigned(signed):
|
||||
value = signed
|
||||
case let .SessionDelegate(delegate):
|
||||
value = delegate
|
||||
case let .VoipEnabled(enabled):
|
||||
value = enabled
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
public func ==(lhs: SocketIOClientOption, rhs: SocketIOClientOption) -> Bool {
|
||||
return lhs.description == rhs.description
|
||||
}
|
||||
|
||||
extension Set where Element: ClientOption {
|
||||
mutating func insertIgnore(element: Element) {
|
||||
if !contains(element) {
|
||||
insert(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension NSDictionary {
|
||||
static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
|
||||
switch (key, value) {
|
||||
case let ("connectParams", params as [String: AnyObject]):
|
||||
return .ConnectParams(params)
|
||||
case let ("reconnects", reconnects as Bool):
|
||||
return .Reconnects(reconnects)
|
||||
case let ("reconnectAttempts", attempts as Int):
|
||||
return .ReconnectAttempts(attempts)
|
||||
case let ("reconnectWait", wait as Int):
|
||||
return .ReconnectWait(wait)
|
||||
case let ("forceNew", force as Bool):
|
||||
return .ForceNew(force)
|
||||
case let ("forcePolling", force as Bool):
|
||||
return .ForcePolling(force)
|
||||
case let ("forceWebsockets", force as Bool):
|
||||
return .ForceWebsockets(force)
|
||||
case let ("nsp", nsp as String):
|
||||
return .Nsp(nsp)
|
||||
case let ("cookies", cookies as [NSHTTPCookie]):
|
||||
return .Cookies(cookies)
|
||||
case let ("log", log as Bool):
|
||||
return .Log(log)
|
||||
case let ("logger", logger as SocketLogger):
|
||||
return .Logger(logger)
|
||||
case let ("sessionDelegate", delegate as NSURLSessionDelegate):
|
||||
return .SessionDelegate(delegate)
|
||||
case let ("path", path as String):
|
||||
return .Path(path)
|
||||
case let ("extraHeaders", headers as [String: String]):
|
||||
return .ExtraHeaders(headers)
|
||||
case let ("handleQueue", queue as dispatch_queue_t):
|
||||
return .HandleQueue(queue)
|
||||
case let ("voipEnabled", enable as Bool):
|
||||
return .VoipEnabled(enable)
|
||||
case let ("secure", secure as Bool):
|
||||
return .Secure(secure)
|
||||
case let ("selfSigned", selfSigned as Bool):
|
||||
return .SelfSigned(selfSigned)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func toSocketOptionsSet() -> Set<SocketIOClientOption> {
|
||||
var options = Set<SocketIOClientOption>()
|
||||
|
||||
for (rawKey, value) in self {
|
||||
if let key = rawKey as? String, opt = NSDictionary.keyValueToSocketIOClientOption(key, value: value) {
|
||||
options.insertIgnore(opt)
|
||||
}
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//
|
||||
// SocketLogger.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 4/11/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 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...)
|
||||
}
|
||||
|
||||
public extension SocketLogger {
|
||||
func log(message: String, type: String, args: AnyObject...) {
|
||||
abstractLog("LOG", message: message, type: type, args: args)
|
||||
}
|
||||
|
||||
func error(message: String, type: String, args: AnyObject...) {
|
||||
abstractLog("ERROR", message: message, type: type, args: args)
|
||||
}
|
||||
|
||||
private func abstractLog(logType: String, message: String, type: String, args: [AnyObject]) {
|
||||
guard log else { return }
|
||||
|
||||
let newArgs = args.map({arg -> CVarArgType in String(arg)})
|
||||
let replaced = String(format: message, arguments: newArgs)
|
||||
|
||||
NSLog("%@ %@: %@", logType, type, replaced)
|
||||
}
|
||||
}
|
||||
|
||||
class DefaultSocketLogger: SocketLogger {
|
||||
static var Logger: SocketLogger = DefaultSocketLogger()
|
||||
|
||||
var log = false
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
//
|
||||
// SocketPacket.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 1/18/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
|
||||
|
||||
struct SocketPacket {
|
||||
private let placeholders: Int
|
||||
|
||||
private static let logType = "SocketPacket"
|
||||
|
||||
let nsp: String
|
||||
let id: Int
|
||||
let type: PacketType
|
||||
|
||||
enum PacketType: Int {
|
||||
case Connect, Disconnect, Event, Ack, Error, BinaryEvent, BinaryAck
|
||||
}
|
||||
|
||||
var args: [AnyObject] {
|
||||
if type == .Event || type == .BinaryEvent && data.count != 0 {
|
||||
return Array(data.dropFirst())
|
||||
} else {
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
var binary: [NSData]
|
||||
var data: [AnyObject]
|
||||
var description: String {
|
||||
return "SocketPacket {type: \(String(type.rawValue)); data: " +
|
||||
"\(String(data)); id: \(id); placeholders: \(placeholders); nsp: \(nsp)}"
|
||||
}
|
||||
|
||||
var event: String {
|
||||
return String(data[0])
|
||||
}
|
||||
|
||||
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 == binary.count {
|
||||
return true
|
||||
}
|
||||
|
||||
binary.append(data)
|
||||
|
||||
if placeholders == binary.count {
|
||||
fillInPlaceholders()
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private func completeMessage(message: String, ack: Bool) -> String {
|
||||
var restOfMessage = ""
|
||||
|
||||
if data.count == 0 {
|
||||
return message + "]"
|
||||
}
|
||||
|
||||
for arg in data {
|
||||
if arg is NSDictionary || arg is [AnyObject] {
|
||||
do {
|
||||
let jsonSend = try NSJSONSerialization.dataWithJSONObject(arg,
|
||||
options: NSJSONWritingOptions(rawValue: 0))
|
||||
let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding)
|
||||
|
||||
restOfMessage += jsonString! + ","
|
||||
} catch {
|
||||
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
|
||||
type: SocketPacket.logType)
|
||||
}
|
||||
} else if let str = arg as? String {
|
||||
restOfMessage += "\"" + ((str["\n"] <~ "\\\\n")["\r"] <~ "\\\\r") + "\","
|
||||
} else if arg is NSNull {
|
||||
restOfMessage += "null,"
|
||||
} else {
|
||||
restOfMessage += "\(arg),"
|
||||
}
|
||||
}
|
||||
|
||||
if restOfMessage != "" {
|
||||
restOfMessage.removeAtIndex(restOfMessage.endIndex.predecessor())
|
||||
}
|
||||
|
||||
return message + restOfMessage + "]"
|
||||
}
|
||||
|
||||
private func createAck() -> String {
|
||||
let message: String
|
||||
|
||||
if type == .Ack {
|
||||
if nsp == "/" {
|
||||
message = "3\(id)["
|
||||
} else {
|
||||
message = "3\(nsp),\(id)["
|
||||
}
|
||||
} else {
|
||||
if nsp == "/" {
|
||||
message = "6\(binary.count)-\(id)["
|
||||
} else {
|
||||
message = "6\(binary.count)-\(nsp),\(id)["
|
||||
}
|
||||
}
|
||||
|
||||
return completeMessage(message, ack: true)
|
||||
}
|
||||
|
||||
|
||||
private func createMessageForEvent() -> String {
|
||||
let message: String
|
||||
|
||||
if type == .Event {
|
||||
if nsp == "/" {
|
||||
if id == -1 {
|
||||
message = "2["
|
||||
} else {
|
||||
message = "2\(id)["
|
||||
}
|
||||
} else {
|
||||
if id == -1 {
|
||||
message = "2\(nsp),["
|
||||
} else {
|
||||
message = "2\(nsp),\(id)["
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if nsp == "/" {
|
||||
if id == -1 {
|
||||
message = "5\(binary.count)-["
|
||||
} else {
|
||||
message = "5\(binary.count)-\(id)["
|
||||
}
|
||||
} else {
|
||||
if id == -1 {
|
||||
message = "5\(binary.count)-\(nsp),["
|
||||
} else {
|
||||
message = "5\(binary.count)-\(nsp),\(id)["
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return completeMessage(message, ack: false)
|
||||
}
|
||||
|
||||
private func createPacketString() -> String {
|
||||
let str: String
|
||||
|
||||
if type == .Event || type == .BinaryEvent {
|
||||
str = createMessageForEvent()
|
||||
} else {
|
||||
str = createAck()
|
||||
}
|
||||
|
||||
return str
|
||||
}
|
||||
|
||||
// Called when we have all the binary data for a packet
|
||||
// calls _fillInPlaceholders, which replaces placeholders with the
|
||||
// corresponding binary
|
||||
private mutating func fillInPlaceholders() {
|
||||
data = data.map(_fillInPlaceholders)
|
||||
}
|
||||
|
||||
// Helper method that looks for placeholder strings
|
||||
// If object is a collection it will recurse
|
||||
// Returns the object if it is not a placeholder string or the corresponding
|
||||
// binary data
|
||||
private func _fillInPlaceholders(object: AnyObject) -> AnyObject {
|
||||
switch object {
|
||||
case let string as String where string["~~(\\d)"].groups() != nil:
|
||||
return binary[Int(string["~~(\\d)"].groups()![1])!]
|
||||
case let dict as NSDictionary:
|
||||
return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in
|
||||
cur[keyValue.0 as! NSCopying] = _fillInPlaceholders(keyValue.1)
|
||||
return cur
|
||||
})
|
||||
case let arr as [AnyObject]:
|
||||
return arr.map(_fillInPlaceholders)
|
||||
default:
|
||||
return object
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SocketPacket {
|
||||
private static func findType(binCount: Int, ack: Bool) -> PacketType {
|
||||
switch binCount {
|
||||
case 0 where !ack:
|
||||
return .Event
|
||||
case 0 where ack:
|
||||
return .Ack
|
||||
case _ where !ack:
|
||||
return .BinaryEvent
|
||||
case _ where ack:
|
||||
return .BinaryAck
|
||||
default:
|
||||
return .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 {
|
||||
// Recursive function that looks for NSData in collections
|
||||
static func shred(data: AnyObject, inout binary: [NSData]) -> AnyObject {
|
||||
let placeholder = ["_placeholder": true, "num": binary.count]
|
||||
|
||||
switch data {
|
||||
case let bin as NSData:
|
||||
binary.append(bin)
|
||||
return placeholder
|
||||
case let arr as [AnyObject]:
|
||||
return arr.map({shred($0, binary: &binary)})
|
||||
case let dict as NSDictionary:
|
||||
return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in
|
||||
cur[keyValue.0 as! NSCopying] = shred(keyValue.1, binary: &binary)
|
||||
return cur
|
||||
})
|
||||
default:
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
// Removes binary data from emit data
|
||||
// Returns a type containing the de-binaryed data and the binary
|
||||
static func deconstructData(data: [AnyObject]) -> ([AnyObject], [NSData]) {
|
||||
var binary = [NSData]()
|
||||
|
||||
return (data.map({shred($0, binary: &binary)}), binary)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//
|
||||
// SocketParsable.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
|
||||
// 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
|
||||
|
||||
protocol SocketParsable: SocketClientSpec {
|
||||
func parseBinaryData(data: NSData)
|
||||
func parseSocketMessage(message: String)
|
||||
}
|
||||
|
||||
extension SocketParsable {
|
||||
private func isCorrectNamespace(nsp: String) -> Bool {
|
||||
return nsp == self.nsp
|
||||
}
|
||||
|
||||
private func handleConnect(p: SocketPacket) {
|
||||
if p.nsp == "/" && nsp != "/" {
|
||||
joinNamespace(nsp)
|
||||
} else if p.nsp != "/" && nsp == "/" {
|
||||
didConnect()
|
||||
} else {
|
||||
didConnect()
|
||||
}
|
||||
}
|
||||
|
||||
private func handlePacket(pack: SocketPacket) {
|
||||
switch pack.type {
|
||||
case .Event where isCorrectNamespace(pack.nsp):
|
||||
handleEvent(pack.event, data: pack.args,
|
||||
isInternalMessage: false, withAck: pack.id)
|
||||
case .Ack where isCorrectNamespace(pack.nsp):
|
||||
handleAck(pack.id, data: pack.data)
|
||||
case .BinaryEvent where isCorrectNamespace(pack.nsp):
|
||||
waitingData.append(pack)
|
||||
case .BinaryAck where isCorrectNamespace(pack.nsp):
|
||||
waitingData.append(pack)
|
||||
case .Connect:
|
||||
handleConnect(pack)
|
||||
case .Disconnect:
|
||||
didDisconnect("Got Disconnect")
|
||||
case .Error:
|
||||
handleEvent("error", data: pack.data, isInternalMessage: true, withAck: pack.id)
|
||||
default:
|
||||
DefaultSocketLogger.Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a messsage from the engine. Returning either a string error or a complete SocketPacket
|
||||
func parseString(message: String) -> Either<String, SocketPacket> {
|
||||
var parser = SocketStringReader(message: message)
|
||||
|
||||
guard let type = SocketPacket.PacketType(rawValue: Int(parser.read(1)) ?? -1) else {
|
||||
return .Left("Invalid packet type")
|
||||
}
|
||||
|
||||
if !parser.hasNext {
|
||||
return .Right(SocketPacket(type: type, nsp: "/"))
|
||||
}
|
||||
|
||||
var namespace: String?
|
||||
var placeholders = -1
|
||||
|
||||
if type == .BinaryEvent || type == .BinaryAck {
|
||||
if let holders = Int(parser.readUntilStringOccurence("-")) {
|
||||
placeholders = holders
|
||||
} else {
|
||||
return .Left("Invalid packet")
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
let d = message[parser.currentIndex.advancedBy(1)..<message.endIndex]
|
||||
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] <~ "\"~~$2\""
|
||||
|
||||
switch parseData(noPlaceholders) {
|
||||
case let .Left(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)
|
||||
}
|
||||
case let .Right(data):
|
||||
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
|
||||
nsp: namespace ?? "/", placeholders: placeholders))
|
||||
}
|
||||
}
|
||||
|
||||
// Parses data for events
|
||||
private func parseData(data: String) -> Either<String, [AnyObject]> {
|
||||
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
||||
do {
|
||||
if let arr = try NSJSONSerialization.JSONObjectWithData(stringData!,
|
||||
options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] {
|
||||
return .Right(arr)
|
||||
} else {
|
||||
return .Left("Expected data array")
|
||||
}
|
||||
} catch {
|
||||
return .Left("Error parsing data for packet")
|
||||
}
|
||||
}
|
||||
|
||||
// Parses messages recieved
|
||||
func parseSocketMessage(message: String) {
|
||||
guard !message.isEmpty else { return }
|
||||
|
||||
DefaultSocketLogger.Logger.log("Parsing %@", type: "SocketParser", args: message)
|
||||
|
||||
switch parseString(message) {
|
||||
case let .Left(err):
|
||||
DefaultSocketLogger.Logger.error("\(err): %@", type: "SocketParser", args: message)
|
||||
case let .Right(pack):
|
||||
DefaultSocketLogger.Logger.log("Decoded packet as: %@", type: "SocketParser", args: pack.description)
|
||||
handlePacket(pack)
|
||||
}
|
||||
}
|
||||
|
||||
func parseBinaryData(data: NSData) {
|
||||
guard !waitingData.isEmpty else {
|
||||
DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser")
|
||||
return
|
||||
}
|
||||
|
||||
// Should execute event?
|
||||
guard waitingData[waitingData.count - 1].addData(data) else {
|
||||
return
|
||||
}
|
||||
|
||||
let packet = waitingData.removeLast()
|
||||
|
||||
if packet.type != .BinaryAck {
|
||||
handleEvent(packet.event, data: packet.args ?? [],
|
||||
isInternalMessage: false, withAck: packet.id)
|
||||
} else {
|
||||
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 = (timeoutAfter: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)
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
//
|
||||
// SwiftRegex.swift
|
||||
// SwiftRegex
|
||||
//
|
||||
// Created by John Holdsworth on 26/06/2014.
|
||||
// Copyright (c) 2014 John Holdsworth.
|
||||
//
|
||||
// $Id: //depot/SwiftRegex/SwiftRegex.swift#37 $
|
||||
//
|
||||
// This code is in the public domain from:
|
||||
// https://github.com/johnno1962/SwiftRegex
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
infix operator <~ { associativity none precedence 130 }
|
||||
|
||||
private var swiftRegexCache = [String: NSRegularExpression]()
|
||||
|
||||
internal final class SwiftRegex: NSObject, BooleanType {
|
||||
var target:String
|
||||
var regex: NSRegularExpression
|
||||
|
||||
init(target:String, pattern:String, options:NSRegularExpressionOptions?) {
|
||||
self.target = target
|
||||
if let regex = swiftRegexCache[pattern] {
|
||||
self.regex = regex
|
||||
} else {
|
||||
do {
|
||||
let regex = try NSRegularExpression(pattern: pattern, options:
|
||||
NSRegularExpressionOptions.DotMatchesLineSeparators)
|
||||
swiftRegexCache[pattern] = regex
|
||||
self.regex = regex
|
||||
} catch let error as NSError {
|
||||
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
|
||||
self.regex = NSRegularExpression()
|
||||
}
|
||||
}
|
||||
super.init()
|
||||
}
|
||||
|
||||
private static func failure(message: String) {
|
||||
fatalError("SwiftRegex: \(message)")
|
||||
}
|
||||
|
||||
private var targetRange: NSRange {
|
||||
return NSRange(location: 0,length: target.utf16.count)
|
||||
}
|
||||
|
||||
private func substring(range: NSRange) -> String? {
|
||||
if range.location != NSNotFound {
|
||||
return (target as NSString).substringWithRange(range)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func doesMatch(options: NSMatchingOptions!) -> Bool {
|
||||
return range(options).location != NSNotFound
|
||||
}
|
||||
|
||||
func range(options: NSMatchingOptions) -> NSRange {
|
||||
return regex.rangeOfFirstMatchInString(target as String, options: [], range: targetRange)
|
||||
}
|
||||
|
||||
func match(options: NSMatchingOptions) -> String? {
|
||||
return substring(range(options))
|
||||
}
|
||||
|
||||
func groups() -> [String]? {
|
||||
return groupsForMatch(regex.firstMatchInString(target as String, options:
|
||||
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange))
|
||||
}
|
||||
|
||||
private func groupsForMatch(match: NSTextCheckingResult?) -> [String]? {
|
||||
guard let match = match else {
|
||||
return nil
|
||||
}
|
||||
var groups = [String]()
|
||||
for groupno in 0...regex.numberOfCaptureGroups {
|
||||
if let group = substring(match.rangeAtIndex(groupno)) {
|
||||
groups += [group]
|
||||
} else {
|
||||
groups += ["_"] // avoids bridging problems
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
subscript(groupno: Int) -> String? {
|
||||
get {
|
||||
return groups()?[groupno]
|
||||
}
|
||||
|
||||
set(newValue) {
|
||||
if newValue == nil {
|
||||
return
|
||||
}
|
||||
|
||||
for match in Array(matchResults().reverse()) {
|
||||
let replacement = regex.replacementStringForResult(match,
|
||||
inString: target as String, offset: 0, template: newValue!)
|
||||
let mut = NSMutableString(string: target)
|
||||
mut.replaceCharactersInRange(match.rangeAtIndex(groupno), withString: replacement)
|
||||
|
||||
target = mut as String
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func matchResults() -> [NSTextCheckingResult] {
|
||||
let matches = regex.matchesInString(target as String, options:
|
||||
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange)
|
||||
as [NSTextCheckingResult]
|
||||
|
||||
return matches
|
||||
}
|
||||
|
||||
func ranges() -> [NSRange] {
|
||||
return matchResults().map { $0.range }
|
||||
}
|
||||
|
||||
func matches() -> [String] {
|
||||
return matchResults().map( { self.substring($0.range)!})
|
||||
}
|
||||
|
||||
func allGroups() -> [[String]?] {
|
||||
return matchResults().map { self.groupsForMatch($0) }
|
||||
}
|
||||
|
||||
func dictionary(options: NSMatchingOptions!) -> Dictionary<String,String> {
|
||||
var out = Dictionary<String,String>()
|
||||
for match in matchResults() {
|
||||
out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))!
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String),
|
||||
options:NSMatchingOptions) -> String {
|
||||
let out = NSMutableString()
|
||||
var pos = 0
|
||||
|
||||
regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {match, flags, stop in
|
||||
let matchRange = match!.range
|
||||
out.appendString( self.substring(NSRange(location:pos, length:matchRange.location-pos))!)
|
||||
out.appendString( substitution(match!, stop) )
|
||||
pos = matchRange.location + matchRange.length
|
||||
}
|
||||
|
||||
out.appendString(substring(NSRange(location:pos, length:targetRange.length-pos))!)
|
||||
|
||||
return out as String
|
||||
}
|
||||
|
||||
var boolValue: Bool {
|
||||
return doesMatch(nil)
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex {
|
||||
return SwiftRegex(target: self, pattern: pattern, options: options)
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
subscript(pattern: String) -> SwiftRegex {
|
||||
return SwiftRegex(target: self, pattern: pattern, options: nil)
|
||||
}
|
||||
}
|
||||
|
||||
func <~ (left: SwiftRegex, right: String) -> String {
|
||||
return left.substituteMatches({match, stop in
|
||||
return left.regex.replacementStringForResult( match,
|
||||
inString: left.target as String, offset: 0, template: right )
|
||||
}, options: [])
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user