Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31a41072c3 | ||
|
|
c325706228 | ||
|
|
a0dff2fea4 | ||
|
|
acdb29dca4 | ||
|
|
0c3e25ef3c | ||
|
|
d8ea3a3c11 | ||
|
|
ac28c7541e | ||
|
|
fcc202ab04 | ||
|
|
eb56a8de9c | ||
|
|
c2d488e35c | ||
|
|
eb9d2bc744 | ||
|
|
a4e81fee6a | ||
|
|
9489676009 | ||
|
|
6e56869ef0 | ||
|
|
dde941f4af | ||
|
|
3ebc596ab8 | ||
|
|
ce81bb2a33 | ||
|
|
1349b01b2b | ||
|
|
63cbf49448 | ||
|
|
a17f2b6e7a | ||
|
|
a1f24ff281 | ||
|
|
838dade0fa | ||
|
|
d4470a9084 | ||
|
|
affd792334 | ||
|
|
c1b0d3abeb | ||
|
|
38163d29cb | ||
|
|
2952120fc1 | ||
|
|
7641ffef41 | ||
|
|
58d2693910 | ||
|
|
dd28b1747c | ||
|
|
e90ecb81be | ||
|
|
060060f5c2 | ||
|
|
f7b064d80f | ||
|
|
918d40d68c | ||
|
|
01a699c7c6 | ||
|
|
5fffa685e9 | ||
|
|
7b7ccb87da | ||
|
|
93f1cfe9dc | ||
|
|
da1cf9eb89 | ||
|
|
a61f1c8484 | ||
|
|
57731bebf8 | ||
|
|
81d58fbd69 | ||
|
|
c4731dc298 | ||
|
|
18a561f78a | ||
|
|
85019cca09 | ||
|
|
a4361a04b6 | ||
|
|
ffcd841267 | ||
|
|
d308111a8f | ||
|
|
f669267f51 | ||
|
|
98e0c355f9 | ||
|
|
2cae405d29 | ||
|
|
f008f116a6 | ||
|
|
77532acbd3 | ||
|
|
9512c8b9ac | ||
|
|
b0020997c4 | ||
|
|
ce7c9c2c15 | ||
|
|
90f50a1c7e | ||
|
|
182ba0017b | ||
|
|
5b897ddfea | ||
|
|
4e6b686f37 | ||
|
|
78aba627a2 | ||
|
|
9044de53d9 | ||
|
|
e34cb61ae2 | ||
|
|
61ad14f23b | ||
|
|
03c24659f2 | ||
|
|
5e1a19f638 | ||
|
|
1d70305743 | ||
|
|
4c7b3175ca | ||
|
|
5533545adb | ||
|
|
8fa8944672 | ||
|
|
dee508c0f7 | ||
|
|
4de422e7f1 | ||
|
|
4629565aaf | ||
|
|
8b893ad85e | ||
|
|
8b3e4a2c43 | ||
|
|
504d0fbd18 | ||
|
|
6985efd7fb | ||
|
|
6ac69d1c2d | ||
|
|
b8b12313fa | ||
|
|
5388084c79 | ||
|
|
48bcada835 | ||
|
|
cf65f56a1d | ||
|
|
18b8f992d9 | ||
|
|
b576294232 | ||
|
|
2837c7c42c | ||
|
|
4832be5c8a | ||
|
|
d70db2a8be | ||
|
|
cbc59d6004 | ||
|
|
72d5c07de1 | ||
|
|
54b2da8395 | ||
|
|
5175791513 | ||
|
|
2f82de9502 | ||
|
|
457a33c677 | ||
|
|
15954f36f5 | ||
|
|
fd3dbee71c | ||
|
|
911cac9c23 | ||
|
|
d13d185011 | ||
|
|
84752b463a | ||
|
|
66aaa52120 | ||
|
|
5b180a0a6d | ||
|
|
bb26dd05f8 | ||
|
|
0ca13c5496 | ||
|
|
1a5487fec5 | ||
|
|
07f2d7465a | ||
|
|
89ae9bd349 | ||
|
|
c67e7a3003 | ||
|
|
472ba50058 | ||
|
|
ab77d7260e | ||
|
|
028afcaa2c | ||
|
|
ac31b4a788 | ||
|
|
7d08f962d5 | ||
|
|
2712461044 | ||
|
|
3ebdd9f7eb | ||
|
|
3e260152cb | ||
|
|
937090458c | ||
|
|
44e2781076 | ||
|
|
fea16879e1 | ||
|
|
e932d0a26b | ||
|
|
6e84950c05 | ||
|
|
90187aa458 | ||
|
|
68da96f37d | ||
|
|
ffd92d7bb4 | ||
|
|
c6d0331d50 | ||
|
|
7765e57a11 | ||
|
|
18c25fabdf | ||
|
|
c103734035 | ||
|
|
2022f282c9 | ||
|
|
d75457f397 | ||
|
|
bb6bd2b4ca | ||
|
|
c177671112 | ||
|
|
94f3e3a6b9 | ||
|
|
4551cad9e1 | ||
|
|
2cc68aead6 | ||
|
|
1f05bde09b | ||
|
|
5b019a91c5 | ||
|
|
a28e924b04 | ||
|
|
f7bf9d4e6b | ||
|
|
37537de213 | ||
|
|
560235353d | ||
|
|
8e7c8444d3 | ||
|
|
74939f1cea | ||
|
|
ab5cccce85 | ||
|
|
58362f6352 | ||
|
|
abbd8e6a67 | ||
|
|
3ba793acf1 | ||
|
|
ea20dc809e | ||
|
|
3e5fe4009c | ||
|
|
a84aa31489 | ||
|
|
8f7f43f83e | ||
|
|
30cd0bd6cd | ||
|
|
ac2bc13b11 | ||
|
|
33f3ef4846 | ||
|
|
f14d9ef5ff | ||
|
|
2e451e5185 | ||
|
|
94d715aaf9 | ||
|
|
1ac05d9790 | ||
|
|
02b1314a3d | ||
|
|
211dc1dd22 | ||
|
|
e7973ba88f | ||
|
|
43ccf6dd45 | ||
|
|
3fbc396d85 | ||
|
|
ecd76d6106 | ||
|
|
50ac79e07e | ||
|
|
5b9537065f | ||
|
|
516d9b3eea | ||
|
|
306ac47168 | ||
|
|
170b1bc836 | ||
|
|
44de79d8c5 | ||
|
|
5d8479ed36 | ||
|
|
3754bd572a | ||
|
|
12b8f3ef1f | ||
|
|
308983c6c7 | ||
|
|
216d8cae1e | ||
|
|
c88febc5bc | ||
|
|
5f179ac278 | ||
|
|
f826ca4b8e | ||
|
|
b53d22f3a2 | ||
|
|
6d6ac0fc74 | ||
|
|
ca00926647 |
No files matched your search
@@ -0,0 +1,230 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-2015 Erik Little
|
||||
|
||||
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.
|
||||
|
||||
|
||||
|
||||
This library makes use of the following third party libraries:
|
||||
|
||||
Starscream
|
||||
----------
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,30 +1,106 @@
|
||||
Socket.IO-Client-Swift
|
||||
======================
|
||||
#Socket.IO-Client-Swift
|
||||
Socket.IO-client for iOS/OS X.
|
||||
|
||||
Socket.IO-client for Swift. Supports ws/wss/polling connections and binary. For socket.io 1.0+ and Swift 1.1.
|
||||
##Example
|
||||
```swift
|
||||
let socket = SocketIOClient(socketURL: "localhost:8080")
|
||||
|
||||
For Swift 1.2 use the 1.2 branch.
|
||||
socket.on("connect") {data, ack in
|
||||
println("socket connected")
|
||||
}
|
||||
|
||||
Installation
|
||||
============
|
||||
socket.on("currentAmount") {data, ack in
|
||||
if let cur = data?[0] as? Double {
|
||||
socket.emitWithAck("canUpdate", cur)(timeout: 0) {data in
|
||||
socket.emit("update", ["amount": cur + 2.50])
|
||||
}
|
||||
|
||||
ack?("Got your currentAmount", "dude")
|
||||
}
|
||||
}
|
||||
|
||||
// Connect
|
||||
socket.connect()
|
||||
```
|
||||
|
||||
##Objective-C Example
|
||||
```objective-c
|
||||
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" options:nil];
|
||||
|
||||
[socket on: @"connect" callback: ^(NSArray* data, void (^ack)(NSArray*)) {
|
||||
NSLog(@"connected");
|
||||
[socket emitObjc:@"echo" withItems:@[@"echo test"]];
|
||||
[socket emitWithAckObjc:@"ackack" withItems:@[@1]](10, ^(NSArray* data) {
|
||||
NSLog(@"Got ack");
|
||||
});
|
||||
}];
|
||||
|
||||
```
|
||||
|
||||
##Features
|
||||
- Supports socket.io 1.0+
|
||||
- Supports binary
|
||||
- Supports Polling and WebSockets
|
||||
- Supports TLS/SSL
|
||||
- Can be used from Objective-C
|
||||
|
||||
##Installation
|
||||
Manually (iOS 7+)
|
||||
-----------------
|
||||
1. Copy the SwiftIO folder into your Xcode project!
|
||||
|
||||
API
|
||||
===
|
||||
Constructor
|
||||
CocoaPods 0.36.0 or later (iOS 8+)
|
||||
------------------
|
||||
Create `Podfile` and add `pod 'Socket.IO-Client-Swift'`:
|
||||
|
||||
```ruby
|
||||
source 'https://github.com/CocoaPods/Specs.git'
|
||||
platform :ios, '8.0'
|
||||
use_frameworks!
|
||||
|
||||
pod 'Socket.IO-Client-Swift', '~> 1.3.2' # Or latest version
|
||||
```
|
||||
|
||||
Install pods:
|
||||
|
||||
```
|
||||
$ pod install
|
||||
```
|
||||
|
||||
Import in your swift file:
|
||||
|
||||
```swift
|
||||
import Socket_IO_Client_Swift
|
||||
```
|
||||
|
||||
##API
|
||||
Constructors
|
||||
-----------
|
||||
`init(socketURL: String, opts:[String: AnyObject]? = nil)` - Constructs a new client for the given URL. opts can be omitted (will use default values. See example)
|
||||
`init(socketURL: String, opts:NSDictionary? = nil)` - Constructs a new client for the given URL. opts can be omitted (will use default values)
|
||||
|
||||
`convenience init(socketURL: String, options:NSDictionary?)` - Same as above, but meant for Objective-C. See Objective-C Example.
|
||||
|
||||
Options
|
||||
-------
|
||||
- `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 `"/"`
|
||||
- `cookies: [NSHTTPCookie]?` An array of NSHTTPCookies. Passed during the handshake. Default is nil.
|
||||
|
||||
Methods
|
||||
-------
|
||||
1. `socket.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. `socket.onAny(callback:((event:String, items:AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
|
||||
3. `socket.emit(event:String, args:AnyObject...)` - Sends a message. Can send multiple args.
|
||||
4. `socket.emitObjc(event:String, args:[AnyObject])` - `emit` for Objective-C
|
||||
5. `socket.emitWithAck(event:String, args:AnyObject...) -> SocketAckHandler` - Sends a message that requests an acknowledgement from the server. Returns a SocketAckHandler which you can use to add an onAck handler. See example.
|
||||
6. `socket.emitWithAckObjc(event:String, _ args:[AnyObject]) -> SocketAckHandler` - `emitWithAck` for Objective-C.
|
||||
7. `socket.connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
|
||||
8. `socket.connectWithParams(params:[String: AnyObject])` - Establishes a connection to the server passing the specified params. A "connect" event is fired upon successful connection.
|
||||
9. `socket.close()` - Closes the socket. Once a socket is closed it should not be reopened.
|
||||
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. `emitObjc(event:String, withItems items:[AnyObject])` - `emit` for Objective-C
|
||||
5. `emitWithAck(event:String, _ items:AnyObject...) -> (timeout:UInt64, callback:(NSArray?) -> Void) -> Void` - Sends a message that requests an acknowledgement from the server. Returns a function which you can use to add a handler. See example. Note: The message is not sent until you call the returned function.
|
||||
6. `emitWithAckObjc(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. `connectWithParams(params:[String: AnyObject])` - Establishes a connection to the server passing the specified params. A "connect" event is fired upon successful connection.
|
||||
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.
|
||||
|
||||
Events
|
||||
------
|
||||
@@ -34,104 +110,8 @@ Events
|
||||
4. `reconnect` - Emitted when the connection is starting to reconnect.
|
||||
5. `reconnectAttempt` - Emitted when attempting to reconnect.
|
||||
|
||||
Example
|
||||
=======
|
||||
```swift
|
||||
// opts can be omitted, will use default values
|
||||
let socket = SocketIOClient(socketURL: "https://localhost:8080", opts: [
|
||||
"reconnects": true, // default true
|
||||
"reconnectAttempts": 5, // default -1 (infinite tries)
|
||||
"reconnectWait": 5, // default 10
|
||||
"nsp": "swift", // connects to the specified namespace. Default is /
|
||||
"forcePolling": true // if true, the socket will only use XHR polling, default is false (polling/WebSockets)
|
||||
])
|
||||
|
||||
// Called on every event
|
||||
socket.onAny {println("got event: \($0.event) with items \($0.items)")}
|
||||
|
||||
// Socket Events
|
||||
socket.on("connect") {data, ack in
|
||||
println("socket connected")
|
||||
|
||||
// Sending messages
|
||||
socket.emit("testEcho")
|
||||
|
||||
socket.emit("testObject", [
|
||||
"data": true
|
||||
])
|
||||
|
||||
// Sending multiple items per message
|
||||
socket.emit("multTest", [1], 1.4, 1, "true",
|
||||
true, ["test": "foo"], "bar")
|
||||
}
|
||||
|
||||
// Requesting acks, and responding to acks
|
||||
socket.on("ackEvent") {data, ack in
|
||||
if let str = data?[0] as? String {
|
||||
println("Got ackEvent")
|
||||
}
|
||||
|
||||
socket.emitWithAck("ackTest", "test").onAck {data in
|
||||
println(data?[0])
|
||||
}
|
||||
|
||||
ack?("Got your event", "dude")
|
||||
}
|
||||
|
||||
socket.on("jsonTest") {data, ack in
|
||||
if let json = data?[0] as? NSDictionary {
|
||||
println(json["test"]!) // foo bar
|
||||
}
|
||||
}
|
||||
|
||||
// Event items are passed by an array
|
||||
socket.on("multipleItems") {data, ack in
|
||||
if data == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if let str = data![0] as? String {
|
||||
println(str)
|
||||
}
|
||||
|
||||
if let arr = data![1] as? [Int] {
|
||||
println(arr)
|
||||
}
|
||||
|
||||
if let obj = data![4] as? NSDictionary {
|
||||
println(obj["test"])
|
||||
}
|
||||
}
|
||||
|
||||
// Connecting
|
||||
socket.connect()
|
||||
|
||||
// Sending binary
|
||||
socket.emit("testData", [
|
||||
"data": "Hello World".dataUsingEncoding(NSUTF8StringEncoding,
|
||||
allowLossyConversion: false)!,
|
||||
"test": true])
|
||||
```
|
||||
|
||||
Objective-C Example
|
||||
===================
|
||||
```objective-c
|
||||
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" opts:nil];
|
||||
|
||||
[socket on: @"connect" callback: ^(NSArray* data, void (^ack)(NSArray*)) {
|
||||
NSLog(@"connected");
|
||||
[socket emitObjc:@"echo" :@[@"echo test"]];
|
||||
[[socket emitWithAckObjc:@"ackack" :@[@"test"]] onAck:^(NSArray* data) {
|
||||
NSLog(@"Got data");
|
||||
}];
|
||||
}];
|
||||
|
||||
```
|
||||
|
||||
Detailed Example
|
||||
================
|
||||
##Detailed Example
|
||||
A more detailed example can be found [here](https://github.com/nuclearace/socket.io-client-swift-example)
|
||||
|
||||
License
|
||||
=======
|
||||
##License
|
||||
MIT
|
||||
@@ -0,0 +1,19 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "Socket.IO-Client-Swift"
|
||||
s.version = "2.0.0"
|
||||
s.summary = "Socket.IO-client for Swift"
|
||||
s.description = <<-DESC
|
||||
Socket.IO-client for Swift.
|
||||
Supports ws/wss/polling connections and binary.
|
||||
For socket.io 1.0+ and Swift 1.1.
|
||||
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.0.0' }
|
||||
s.source_files = "SwiftIO/**/*.swift"
|
||||
s.requires_arc = true
|
||||
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
|
||||
end
|
||||
@@ -0,0 +1,63 @@
|
||||
//
|
||||
// SocketAckMap.swift
|
||||
// SocketIO-Swift
|
||||
//
|
||||
// Created by Erik Little on 4/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
|
||||
|
||||
// @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 OnAckCallback = (timeout:UInt64, callback:AckCallback) -> Void
|
||||
|
||||
struct SocketAckMap {
|
||||
private var acks = [Int: AckCallback]()
|
||||
private var waiting = [Int: Bool]()
|
||||
|
||||
mutating func addAck(ack:Int, callback:AckCallback) {
|
||||
waiting[ack] = true
|
||||
acks[ack] = callback
|
||||
}
|
||||
|
||||
mutating func executeAck(ack:Int, items:[AnyObject]?) {
|
||||
let callback = acks[ack]
|
||||
waiting[ack] = false
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
callback?(items)
|
||||
return
|
||||
}
|
||||
|
||||
acks.removeValueForKey(ack)
|
||||
}
|
||||
|
||||
mutating func timeoutAck(ack:Int) {
|
||||
if waiting[ack] != nil && waiting[ack]! {
|
||||
acks[ack]?(["NO ACK"])
|
||||
}
|
||||
|
||||
acks.removeValueForKey(ack)
|
||||
waiting.removeValueForKey(ack)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
//
|
||||
// SocketAckHandler.swift
|
||||
// SocketAnyEvent.swift
|
||||
// Socket.IO-Swift
|
||||
//
|
||||
// Created by Erik Little on 2/14/15.
|
||||
|
||||
// Created by Erik Little on 3/28/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
|
||||
@@ -24,26 +24,12 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
public typealias AckCallback = (NSArray?) -> Void
|
||||
|
||||
@objc public class SocketAckHandler {
|
||||
let ackNum:Int!
|
||||
let event:String!
|
||||
var callback:AckCallback?
|
||||
@objc public class SocketAnyEvent {
|
||||
public let event:String!
|
||||
public var items:[AnyObject]?
|
||||
|
||||
init(event:String, ackNum:Int = 0) {
|
||||
self.ackNum = ackNum
|
||||
init(event:String, items:[AnyObject]?) {
|
||||
self.event = event
|
||||
}
|
||||
|
||||
func onAck(callback:AckCallback) {
|
||||
self.callback = callback
|
||||
}
|
||||
|
||||
func executeAck(data:NSArray?) {
|
||||
dispatch_async(dispatch_get_main_queue()) {[cb = self.callback] in
|
||||
cb?(data)
|
||||
return
|
||||
}
|
||||
self.items = items
|
||||
}
|
||||
}
|
||||
+399
-292
@@ -24,19 +24,16 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
// This is used because in Swift 1.1, turning on -O causes a
|
||||
// memory access violation in SocketEngine#parseEngineMessage
|
||||
private var fixSwift:AnyObject?
|
||||
|
||||
extension String {
|
||||
private var length:Int {
|
||||
return countElements(self)
|
||||
return count(self)
|
||||
}
|
||||
}
|
||||
|
||||
private typealias PollWaitQueue = [() -> Void]
|
||||
private typealias Probe = (msg:String, type:PacketType, data:ContiguousArray<NSData>?)
|
||||
private typealias ProbeWaitQueue = [Probe]
|
||||
|
||||
private enum PacketType: String {
|
||||
public enum PacketType:String {
|
||||
case OPEN = "0"
|
||||
case CLOSE = "1"
|
||||
case PING = "2"
|
||||
@@ -46,27 +43,35 @@ private enum PacketType: String {
|
||||
case NOOP = "6"
|
||||
}
|
||||
|
||||
class SocketEngine: NSObject, WebSocketDelegate {
|
||||
unowned let client:SocketIOClient
|
||||
public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
private let workQueue = NSOperationQueue()
|
||||
private let emitQueue = dispatch_queue_create(
|
||||
"emitQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||
"engineEmitQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||
private let parseQueue = dispatch_queue_create(
|
||||
"parseQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||
"engineParseQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||
private let handleQueue = dispatch_queue_create(
|
||||
"handleQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||
"engineHandleQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||
private let session:NSURLSession!
|
||||
private var closed = false
|
||||
private var _connected = false
|
||||
private var fastUpgrade = false
|
||||
private var forcePolling = false
|
||||
private var forceWebsockets = false
|
||||
private var pingTimer:NSTimer?
|
||||
private var postWait = [String]()
|
||||
private var _polling = true
|
||||
private var probing = false
|
||||
private var probeWait = PollWaitQueue()
|
||||
private let session:NSURLSession!
|
||||
private var probeWait = ProbeWaitQueue()
|
||||
private var waitingForPoll = false
|
||||
private var waitingForPost = false
|
||||
private var _websocket = false
|
||||
private var websocketConnected = false
|
||||
var connected = false
|
||||
var connected:Bool {
|
||||
return self._connected
|
||||
}
|
||||
|
||||
weak var client:SocketEngineClient?
|
||||
var cookies:[NSHTTPCookie]?
|
||||
var pingInterval:Int?
|
||||
var polling:Bool {
|
||||
return self._polling
|
||||
@@ -78,19 +83,29 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
||||
return self._websocket
|
||||
}
|
||||
var ws:WebSocket?
|
||||
|
||||
init(client:SocketIOClient, forcePolling:Bool = false) {
|
||||
self.client = client
|
||||
self.forcePolling = forcePolling
|
||||
self.session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
|
||||
delegate: nil, delegateQueue: self.workQueue)
|
||||
|
||||
public init(client:SocketEngineClient, forcePolling:Bool,
|
||||
forceWebsockets:Bool, withCookies cookies:[NSHTTPCookie]?) {
|
||||
self.client = client
|
||||
self.forcePolling = forcePolling
|
||||
self.forceWebsockets = forceWebsockets
|
||||
self.cookies = cookies
|
||||
self.session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
|
||||
delegate: nil, delegateQueue: self.workQueue)
|
||||
}
|
||||
|
||||
func close() {
|
||||
|
||||
public func close(#fast:Bool) {
|
||||
self.pingTimer?.invalidate()
|
||||
self.send(PacketType.CLOSE.rawValue)
|
||||
self.closed = true
|
||||
|
||||
self.write("", withType: PacketType.CLOSE, withData: nil)
|
||||
self.ws?.disconnect()
|
||||
|
||||
if fast || self.polling {
|
||||
self.client?.didForceClose("Disconnect")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private func createBinaryDataForSend(data:NSData) -> (NSData?, String?) {
|
||||
if self.websocket {
|
||||
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
|
||||
@@ -102,33 +117,37 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
||||
var str = "b4"
|
||||
str += data.base64EncodedStringWithOptions(
|
||||
NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
|
||||
|
||||
|
||||
return (nil, str)
|
||||
}
|
||||
}
|
||||
|
||||
private func createURLs(params:[String: AnyObject]? = nil) -> (String, String) {
|
||||
var url = "\(self.client.socketURL)/socket.io/?transport="
|
||||
|
||||
private func createURLs(params:[String: AnyObject]?) -> (String, String) {
|
||||
if self.client == nil {
|
||||
return ("", "")
|
||||
}
|
||||
|
||||
var url = "\(self.client!.socketURL)/socket.io/?transport="
|
||||
var urlPolling:String
|
||||
var urlWebSocket:String
|
||||
|
||||
if self.client.secure {
|
||||
|
||||
if self.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(
|
||||
NSCharacterSet.URLHostAllowedCharacterSet())!
|
||||
urlPolling += "&\(keyEsc)="
|
||||
urlWebSocket += "&\(keyEsc)="
|
||||
|
||||
|
||||
if value is String {
|
||||
let valueEsc = (value as String).stringByAddingPercentEncodingWithAllowedCharacters(
|
||||
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
|
||||
NSCharacterSet.URLHostAllowedCharacterSet())!
|
||||
urlPolling += "\(valueEsc)"
|
||||
urlWebSocket += "\(valueEsc)"
|
||||
@@ -138,64 +157,105 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return (urlPolling, urlWebSocket)
|
||||
}
|
||||
|
||||
|
||||
private func createWebsocket(andConnect connect:Bool) {
|
||||
self.ws = WebSocket(url: NSURL(string: self.urlWebSocket! + "&sid=\(self.sid)")!)
|
||||
self.ws?.queue = self.handleQueue
|
||||
self.ws?.delegate = self
|
||||
|
||||
if connect {
|
||||
self.ws?.connect()
|
||||
}
|
||||
}
|
||||
|
||||
private func doFastUpgrade() {
|
||||
if self.waitingForPoll {
|
||||
NSLog("Outstanding poll when switched to websockets," +
|
||||
"we'll probably disconnect soon. You should report this.")
|
||||
}
|
||||
|
||||
self.sendWebSocketMessage("", withType: PacketType.UPGRADE, datas: nil)
|
||||
self._websocket = true
|
||||
self._polling = false
|
||||
self.fastUpgrade = false
|
||||
self.probing = false
|
||||
self.flushProbeWait()
|
||||
}
|
||||
|
||||
private func doPoll() {
|
||||
if self.urlPolling == nil || self.websocket || self.waitingForPoll || !self.connected {
|
||||
if self.websocket || self.waitingForPoll || !self.connected {
|
||||
return
|
||||
}
|
||||
|
||||
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
|
||||
req.timeoutInterval = 0.0
|
||||
|
||||
self.waitingForPoll = true
|
||||
|
||||
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)&b64=1")!)
|
||||
|
||||
self.doRequest(req)
|
||||
}
|
||||
|
||||
private func doRequest(req:NSMutableURLRequest) {
|
||||
if !self.polling {
|
||||
return
|
||||
}
|
||||
|
||||
req.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
|
||||
|
||||
// NSLog("Doing request: \(req)")
|
||||
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
||||
if self == nil {
|
||||
return
|
||||
} else if err != nil {
|
||||
if self!.polling {
|
||||
self?.handlePollingFailed(err)
|
||||
self?.handlePollingFailed(err.localizedDescription)
|
||||
} else {
|
||||
NSLog(err.localizedDescription)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// println(data)
|
||||
|
||||
|
||||
// NSLog("Got response: \(res)")
|
||||
|
||||
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
|
||||
// println(str)
|
||||
|
||||
dispatch_async(self!.parseQueue) {[weak self] in
|
||||
if self == nil {
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(self!.parseQueue) {
|
||||
self?.parsePollingMessage(str)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
self?.waitingForPoll = false
|
||||
self?.doPoll()
|
||||
|
||||
if self!.fastUpgrade {
|
||||
self?.doFastUpgrade()
|
||||
return
|
||||
} else if !self!.closed && self!.polling {
|
||||
self?.doPoll()
|
||||
}
|
||||
}.resume()
|
||||
}
|
||||
|
||||
|
||||
private func flushProbeWait() {
|
||||
// println("flushing probe wait")
|
||||
// NSLog("flushing probe wait")
|
||||
dispatch_async(self.emitQueue) {[weak self] in
|
||||
if self == nil {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
for waiter in self!.probeWait {
|
||||
waiter()
|
||||
self?.write(waiter.msg, withType: waiter.type, withData: waiter.data)
|
||||
}
|
||||
|
||||
|
||||
self?.probeWait.removeAll(keepCapacity: false)
|
||||
|
||||
if self?.postWait.count != 0 {
|
||||
self?.flushWaitingForPostToWebSocket()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private func flushWaitingForPost() {
|
||||
if self.postWait.count == 0 || !self.connected {
|
||||
return
|
||||
@@ -203,377 +263,424 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
||||
self.flushWaitingForPostToWebSocket()
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
var postStr = ""
|
||||
|
||||
|
||||
for packet in self.postWait {
|
||||
let len = countElements(packet)
|
||||
|
||||
let len = count(packet)
|
||||
|
||||
postStr += "\(len):\(packet)"
|
||||
}
|
||||
|
||||
|
||||
self.postWait.removeAll(keepCapacity: false)
|
||||
|
||||
|
||||
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
|
||||
|
||||
|
||||
req.HTTPMethod = "POST"
|
||||
req.setValue("application/html-text", forHTTPHeaderField: "Content-Type")
|
||||
|
||||
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
|
||||
|
||||
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
|
||||
allowLossyConversion: false)!
|
||||
|
||||
|
||||
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
|
||||
|
||||
req.HTTPBody = postData
|
||||
|
||||
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
|
||||
|
||||
self.waitingForPost = true
|
||||
|
||||
|
||||
// NSLog("posting: \(postStr)")
|
||||
// NSLog("Posting with WS status of: \(self.websocket)")
|
||||
|
||||
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
||||
if self == nil {
|
||||
return
|
||||
} else if err != nil && self!.polling {
|
||||
self?.handlePollingFailed(err)
|
||||
self?.handlePollingFailed(err.localizedDescription)
|
||||
return
|
||||
} else if err != nil {
|
||||
NSLog(err.localizedDescription)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
self?.waitingForPost = false
|
||||
dispatch_async(self!.emitQueue) {
|
||||
self?.flushWaitingForPost()
|
||||
self?.doPoll()
|
||||
return
|
||||
if !self!.fastUpgrade {
|
||||
self?.flushWaitingForPost()
|
||||
self?.doPoll()
|
||||
}
|
||||
}}.resume()
|
||||
}
|
||||
|
||||
|
||||
// We had packets waiting for send when we upgraded
|
||||
// Send them raw
|
||||
private func flushWaitingForPostToWebSocket() {
|
||||
for msg in self.postWait {
|
||||
self.ws?.writeString(msg)
|
||||
}
|
||||
|
||||
|
||||
self.postWait.removeAll(keepCapacity: true)
|
||||
}
|
||||
|
||||
|
||||
// A poll failed, tell the client about it
|
||||
// We check to see if we were closed by the server first
|
||||
private func handlePollingFailed(reason:NSError?) {
|
||||
if !self.client.reconnecting {
|
||||
self.connected = false
|
||||
self.ws?.disconnect()
|
||||
self.pingTimer?.invalidate()
|
||||
self.waitingForPoll = false
|
||||
self.waitingForPost = false
|
||||
self.client.pollingDidFail(reason)
|
||||
|
||||
private func handlePollingFailed(reason:String) {
|
||||
self._connected = false
|
||||
self.ws?.disconnect()
|
||||
self.pingTimer?.invalidate()
|
||||
self.waitingForPoll = false
|
||||
self.waitingForPost = false
|
||||
|
||||
if self.client == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if !self.closed && !self.client!.reconnecting {
|
||||
self.client?.pollingDidFail(reason)
|
||||
} else if !self.client!.reconnecting {
|
||||
self.client?.didForceClose(reason)
|
||||
}
|
||||
}
|
||||
|
||||
func open(opts:[String: AnyObject]? = nil) {
|
||||
if self.waitingForPost || self.waitingForPoll || self.websocket || self.connected {
|
||||
assert(false, "We're in a bad state, this shouldn't happen.")
|
||||
|
||||
public func open(opts:[String: AnyObject]? = nil) {
|
||||
if self.connected {
|
||||
fatalError("Engine tried to open while connected")
|
||||
}
|
||||
|
||||
let (urlPolling, urlWebSocket) = self.createURLs(params: opts)
|
||||
|
||||
|
||||
self.closed = false
|
||||
let (urlPolling, urlWebSocket) = self.createURLs(opts)
|
||||
self.urlPolling = urlPolling
|
||||
self.urlWebSocket = urlWebSocket
|
||||
let reqPolling = NSURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
|
||||
|
||||
self.session.dataTaskWithRequest(reqPolling) {[weak self] data, res, err in
|
||||
var err2:NSError?
|
||||
if self == nil {
|
||||
return
|
||||
} else if err != nil || data == nil {
|
||||
self?.handlePollingFailed(err)
|
||||
return
|
||||
}
|
||||
|
||||
if let dataString = NSString(data: data, encoding: NSUTF8StringEncoding) {
|
||||
var mutString = RegexMutable(dataString)
|
||||
let parsed:[String]? = mutString["(\\d*):(\\d)(\\{.*\\})?"].groups()
|
||||
|
||||
if parsed == nil || parsed?.count != 4 {
|
||||
return
|
||||
}
|
||||
|
||||
let length = parsed![1]
|
||||
let type = parsed![2]
|
||||
let jsonData = parsed![3].dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
||||
|
||||
if type != "0" {
|
||||
NSLog("Error handshaking")
|
||||
return
|
||||
}
|
||||
|
||||
self?.connected = true
|
||||
|
||||
if let json = NSJSONSerialization.JSONObjectWithData(jsonData!,
|
||||
options: NSJSONReadingOptions.AllowFragments, error: &err2) as? NSDictionary {
|
||||
if let sid = json["sid"] as? String {
|
||||
// println(json)
|
||||
self?.sid = sid
|
||||
|
||||
if !self!.forcePolling {
|
||||
self?.ws = WebSocket(url: NSURL(string: urlWebSocket + "&sid=\(self!.sid)")!)
|
||||
self?.ws?.queue = self?.handleQueue
|
||||
self?.ws?.delegate = self
|
||||
self?.ws?.connect()
|
||||
}
|
||||
} else {
|
||||
NSLog("Error handshaking")
|
||||
return
|
||||
}
|
||||
|
||||
if let pingInterval = json["pingInterval"] as? Int {
|
||||
self?.pingInterval = pingInterval / 1000
|
||||
}
|
||||
}
|
||||
|
||||
self?.doPoll()
|
||||
self?.startPingTimer()
|
||||
}}.resume()
|
||||
|
||||
if self.forceWebsockets {
|
||||
self._polling = false
|
||||
self._websocket = true
|
||||
self.createWebsocket(andConnect: true)
|
||||
return
|
||||
}
|
||||
|
||||
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
|
||||
|
||||
if self.cookies != nil {
|
||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
|
||||
reqPolling.allHTTPHeaderFields = headers
|
||||
}
|
||||
|
||||
self.doRequest(reqPolling)
|
||||
}
|
||||
|
||||
|
||||
// Translatation of engine.io-parser#decodePayload
|
||||
private func parsePollingMessage(str:String) {
|
||||
if str.length == 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
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
for var i = 0, l = str.length; i < l; i = i &+ 1 {
|
||||
let chr = String(strArray[i])
|
||||
|
||||
|
||||
if chr != ":" {
|
||||
length += chr
|
||||
} else {
|
||||
if length == "" || testLength(length, &n) {
|
||||
self.handlePollingFailed(nil)
|
||||
NSLog("parsing error: \(str)")
|
||||
self.handlePollingFailed("Error parsing XHR message")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
msg = String(strArray[i&+1...i&+n])
|
||||
|
||||
|
||||
if let lengthInt = length.toInt() {
|
||||
if lengthInt != msg.length {
|
||||
println("parsing error")
|
||||
NSLog("parsing error: \(str)")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if msg.length != 0 {
|
||||
// Be sure to capture the value of the msg
|
||||
dispatch_async(self.handleQueue) {[weak self, msg] in
|
||||
fixSwift = msg
|
||||
if fixSwift is String {
|
||||
self?.parseEngineMessage(fixSwift as String)
|
||||
}
|
||||
self?.parseEngineMessage(msg, fromPolling: true)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
i += n
|
||||
length = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private func parseEngineData(data:NSData) {
|
||||
self.client.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
|
||||
}
|
||||
|
||||
private func parseEngineMessage(var message:String) {
|
||||
// println(message!)
|
||||
|
||||
var strMessage = RegexMutable(message)
|
||||
|
||||
// We should upgrade
|
||||
if strMessage == "3probe" {
|
||||
self.upgradeTransport()
|
||||
if self.client == nil {
|
||||
return
|
||||
}
|
||||
|
||||
let type = strMessage["^(\\d)"].groups()?[1]
|
||||
|
||||
|
||||
dispatch_async(self.client!.handleQueue) {[weak self] in
|
||||
self?.client?.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
private func parseEngineMessage(var message:String, fromPolling:Bool) {
|
||||
// NSLog("Engine got message: \(message)")
|
||||
if fromPolling {
|
||||
fixDoubleUTF8(&message)
|
||||
}
|
||||
|
||||
let type = message["^(\\d)"].groups()?[1]
|
||||
|
||||
if type != PacketType.MESSAGE.rawValue {
|
||||
// TODO Handle other packets
|
||||
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) {
|
||||
// println("sending \(data)")
|
||||
self.client.parseBinaryData(data)
|
||||
|
||||
if self.client == nil {
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(self.client!.handleQueue) {[weak self] in
|
||||
self?.client?.parseBinaryData(data)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return
|
||||
} else if type == PacketType.NOOP.rawValue {
|
||||
self.doPoll()
|
||||
return
|
||||
}
|
||||
|
||||
if message == PacketType.CLOSE.rawValue {
|
||||
// do nothing
|
||||
} else if type == PacketType.PONG.rawValue {
|
||||
// We should upgrade
|
||||
if message == "3probe" {
|
||||
self.upgradeTransport()
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
} else if type == PacketType.OPEN.rawValue {
|
||||
var err:NSError?
|
||||
|
||||
message.removeAtIndex(message.startIndex)
|
||||
let mesData = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
|
||||
|
||||
if let json = NSJSONSerialization.JSONObjectWithData(mesData,
|
||||
options: NSJSONReadingOptions.AllowFragments, error: &err) as? NSDictionary {
|
||||
if let sid = json["sid"] as? String {
|
||||
// println(json)
|
||||
self.sid = sid
|
||||
self._connected = true
|
||||
if !self.forcePolling && !self.forceWebsockets {
|
||||
self.createWebsocket(andConnect: true)
|
||||
}
|
||||
} else {
|
||||
NSLog("Error handshaking")
|
||||
return
|
||||
}
|
||||
|
||||
if let pingInterval = json["pingInterval"] as? Int {
|
||||
self.pingInterval = pingInterval / 1000
|
||||
}
|
||||
} else {
|
||||
fatalError("Error parsing engine connect")
|
||||
}
|
||||
|
||||
self.startPingTimer()
|
||||
|
||||
if !self.forceWebsockets {
|
||||
self.doPoll()
|
||||
}
|
||||
|
||||
return
|
||||
} else if type == PacketType.CLOSE.rawValue {
|
||||
if self.client == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if self.polling {
|
||||
self.client!.didForceClose("Disconnect")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
// println("Got something idk what to do with")
|
||||
// println(messageString)
|
||||
}
|
||||
|
||||
|
||||
// Remove message type
|
||||
message.removeAtIndex(message.startIndex)
|
||||
// println("sending \(messageString)")
|
||||
|
||||
self.client.parseSocketMessage(message)
|
||||
|
||||
if self.client == nil {
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(self.client!.handleQueue) {[weak self] in
|
||||
self?.client?.parseSocketMessage(message)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private func probeWebSocket() {
|
||||
if self.websocketConnected {
|
||||
self.sendWebSocketMessage("probe", withType: PacketType.PING)
|
||||
}
|
||||
}
|
||||
|
||||
func send(msg:String, datas:[NSData]? = nil) {
|
||||
let _send = {[weak self] (msg:String, datas:[NSData]?) -> () -> Void in
|
||||
return {
|
||||
if self == nil || !self!.connected {
|
||||
return
|
||||
}
|
||||
|
||||
if self!.websocket {
|
||||
// println("sending ws: \(msg):\(datas)")
|
||||
self?.sendWebSocketMessage(msg, withType: PacketType.MESSAGE, datas: datas)
|
||||
} else {
|
||||
// println("sending poll: \(msg):\(datas)")
|
||||
self?.sendPollMessage(msg, withType: PacketType.MESSAGE, datas: datas)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dispatch_async(self.emitQueue) {[weak self] in
|
||||
if self == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if self!.probing {
|
||||
self?.probeWait.append(_send(msg, datas))
|
||||
} else {
|
||||
_send(msg, datas)()
|
||||
}
|
||||
|
||||
/// Send an engine message (4)
|
||||
public func send(msg:String, withData datas:ContiguousArray<NSData>?) {
|
||||
if self.probing {
|
||||
self.probeWait.append((msg, PacketType.MESSAGE, datas))
|
||||
} else {
|
||||
self.write(msg, withType: PacketType.MESSAGE, withData: datas)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func sendPing() {
|
||||
if self.websocket {
|
||||
self.sendWebSocketMessage("", withType: PacketType.PING)
|
||||
} else {
|
||||
self.sendPollMessage("", withType: PacketType.PING)
|
||||
}
|
||||
self.write("", withType: PacketType.PING, withData: nil)
|
||||
}
|
||||
|
||||
private func sendPollMessage(msg:String, withType type:PacketType, datas:[NSData]? = nil) {
|
||||
// println("Sending: poll: \(msg) as type: \(type.rawValue)")
|
||||
let strMsg = "\(type.rawValue)\(msg)"
|
||||
|
||||
self.postWait.append(strMsg)
|
||||
|
||||
if datas != nil {
|
||||
for data in datas! {
|
||||
let (nilData, b64Data) = self.createBinaryDataForSend(data)
|
||||
|
||||
self.postWait.append(b64Data!)
|
||||
}
|
||||
}
|
||||
|
||||
if waitingForPost {
|
||||
self.doPoll()
|
||||
return
|
||||
} else {
|
||||
self.flushWaitingForPost()
|
||||
}
|
||||
}
|
||||
|
||||
private func sendWebSocketMessage(str:String, withType type:PacketType, datas:[NSData]? = nil) {
|
||||
// println("Sending: ws: \(str) as type: \(type.rawValue)")
|
||||
self.ws?.writeString("\(type.rawValue)\(str)")
|
||||
|
||||
if datas != nil {
|
||||
for data in datas! {
|
||||
let (data, nilString) = self.createBinaryDataForSend(data)
|
||||
if data != nil {
|
||||
self.ws?.writeData(data!)
|
||||
|
||||
/// Send polling message.
|
||||
/// Only call on emitQueue
|
||||
private func sendPollMessage(var msg:String, withType type:PacketType,
|
||||
datas:ContiguousArray<NSData>? = nil) {
|
||||
// println("Sending poll: \(msg) as type: \(type.rawValue)")
|
||||
doubleEncodeUTF8(&msg)
|
||||
let strMsg = "\(type.rawValue)\(msg)"
|
||||
|
||||
self.postWait.append(strMsg)
|
||||
|
||||
if datas != nil {
|
||||
for data in datas! {
|
||||
let (nilData, b64Data) = self.createBinaryDataForSend(data)
|
||||
|
||||
self.postWait.append(b64Data!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !self.waitingForPost {
|
||||
self.flushWaitingForPost()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Send message on WebSockets
|
||||
/// Only call on emitQueue
|
||||
private func sendWebSocketMessage(str:String, withType type:PacketType,
|
||||
datas:ContiguousArray<NSData>? = nil) {
|
||||
// println("Sending ws: \(str) as type: \(type.rawValue)")
|
||||
self.ws?.writeString("\(type.rawValue)\(str)")
|
||||
|
||||
if datas != nil {
|
||||
for data in datas! {
|
||||
let (data, nilString) = self.createBinaryDataForSend(data)
|
||||
if data != nil {
|
||||
self.ws?.writeData(data!)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Starts the ping timer
|
||||
private func startPingTimer() {
|
||||
if self.pingInterval == nil {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
self.pingTimer?.invalidate()
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(self.pingInterval!), target: self,
|
||||
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(self.pingInterval!),
|
||||
target: self,
|
||||
selector: Selector("sendPing"), userInfo: nil, repeats: true)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private func upgradeTransport() {
|
||||
if self.websocketConnected {
|
||||
self.probing = false
|
||||
self._websocket = true
|
||||
self.waitingForPoll = false
|
||||
self._polling = false
|
||||
self.sendWebSocketMessage("", withType: PacketType.UPGRADE)
|
||||
self.flushProbeWait()
|
||||
// NSLog("Doing fast upgrade")
|
||||
// Do a fast upgrade
|
||||
// At this point, we should not send anymore polling messages-
|
||||
self.fastUpgrade = true
|
||||
self.sendPollMessage("", withType: PacketType.NOOP)
|
||||
}
|
||||
}
|
||||
|
||||
func websocketDidConnect(socket:WebSocket) {
|
||||
self.websocketConnected = true
|
||||
self.probing = true
|
||||
self.probeWebSocket()
|
||||
|
||||
public func write(msg:String, withType type:PacketType, withData data:ContiguousArray<NSData>?) {
|
||||
dispatch_async(self.emitQueue) {[weak self] in
|
||||
if self == nil || !self!.connected {
|
||||
return
|
||||
}
|
||||
|
||||
if self!.websocket {
|
||||
// NSLog("writing ws: \(msg):\(data)")
|
||||
self?.sendWebSocketMessage(msg, withType: type, datas: data)
|
||||
} else {
|
||||
// NSLog("writing poll: \(msg):\(data)")
|
||||
self?.sendPollMessage(msg, withType: type, datas: data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
|
||||
|
||||
// Delagate methods
|
||||
|
||||
public func websocketDidConnect(socket:WebSocket) {
|
||||
self.websocketConnected = true
|
||||
|
||||
if !self.forceWebsockets {
|
||||
self.probing = true
|
||||
self.probeWebSocket()
|
||||
} else {
|
||||
self._connected = true
|
||||
self.probing = false
|
||||
self._polling = false
|
||||
}
|
||||
}
|
||||
|
||||
public func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
|
||||
self.websocketConnected = false
|
||||
self.probing = false
|
||||
|
||||
|
||||
if self.closed {
|
||||
self.client?.didForceClose("Disconnect")
|
||||
return
|
||||
}
|
||||
|
||||
if self.websocket {
|
||||
self.pingTimer?.invalidate()
|
||||
self.connected = false
|
||||
self._connected = false
|
||||
self._websocket = false
|
||||
self._polling = true
|
||||
self.client.webSocketDidCloseWithCode(1, reason: "Socket Disconnect", wasClean: true)
|
||||
|
||||
let reason = error?.localizedDescription
|
||||
self.client?.webSocketDidCloseWithCode(1,
|
||||
reason: reason == nil ? "Socket Disconnected" : reason!)
|
||||
} else {
|
||||
self.flushProbeWait()
|
||||
}
|
||||
}
|
||||
|
||||
func websocketDidReceiveMessage(socket:WebSocket, text:String) {
|
||||
self.parseEngineMessage(text)
|
||||
|
||||
public func websocketDidReceiveMessage(socket:WebSocket, text:String) {
|
||||
self.parseEngineMessage(text, fromPolling: false)
|
||||
}
|
||||
|
||||
func websocketDidReceiveData(socket:WebSocket, data:NSData) {
|
||||
|
||||
public func websocketDidReceiveData(socket:WebSocket, data:NSData) {
|
||||
self.parseEngineData(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//
|
||||
// SocketEngineClient.swift
|
||||
// Socket.IO-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/19/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 SocketEngineClient {
|
||||
var handleQueue:dispatch_queue_attr_t! {get}
|
||||
var emitQueue:dispatch_queue_attr_t! {get}
|
||||
var reconnecting:Bool {get}
|
||||
var socketURL:String {get}
|
||||
var secure:Bool {get}
|
||||
|
||||
func didForceClose(reason:String)
|
||||
func parseSocketMessage(msg:String)
|
||||
func parseBinaryData(data:NSData)
|
||||
func pollingDidFail(err:String)
|
||||
func webSocketDidCloseWithCode(code:Int, reason:String)
|
||||
func webSocketDidFailWithError(error:NSError)
|
||||
}
|
||||
@@ -1,255 +0,0 @@
|
||||
//
|
||||
// Event.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
|
||||
|
||||
class SocketEvent {
|
||||
let justAck:Bool!
|
||||
var ack:Int?
|
||||
var args:AnyObject!
|
||||
lazy var currentPlace = 0
|
||||
lazy var datas = [NSData]()
|
||||
var event:String!
|
||||
var placeholders:Int!
|
||||
|
||||
init(event:String, args:AnyObject?, placeholders:Int = 0, ackNum:Int? = nil, justAck:Bool = false) {
|
||||
self.event = event
|
||||
self.args = args
|
||||
self.placeholders = placeholders
|
||||
self.ack = ackNum
|
||||
self.justAck = justAck
|
||||
}
|
||||
|
||||
func addData(data:NSData) -> Bool {
|
||||
func checkDoEvent() -> Bool {
|
||||
if self.placeholders == self.currentPlace {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if checkDoEvent() {
|
||||
return true
|
||||
}
|
||||
|
||||
self.datas.append(data)
|
||||
self.currentPlace++
|
||||
|
||||
if checkDoEvent() {
|
||||
self.currentPlace = 0
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
class func createMessageForEvent(event:String, withArgs args:[AnyObject],
|
||||
hasBinary:Bool, withDatas datas:Int = 0, toNamespace nsp:String?, wantsAck ack:Int? = nil) -> String {
|
||||
|
||||
var message:String
|
||||
var jsonSendError:NSError?
|
||||
|
||||
if !hasBinary {
|
||||
if nsp == nil {
|
||||
if ack == nil {
|
||||
message = "2[\"\(event)\""
|
||||
} else {
|
||||
message = "2\(ack!)[\"\(event)\""
|
||||
}
|
||||
} else {
|
||||
if ack == nil {
|
||||
message = "2/\(nsp!),[\"\(event)\""
|
||||
} else {
|
||||
message = "2/\(nsp!),\(ack!)[\"\(event)\""
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if nsp == nil {
|
||||
if ack == nil {
|
||||
message = "5\(datas)-[\"\(event)\""
|
||||
} else {
|
||||
message = "5\(datas)-\(ack!)[\"\(event)\""
|
||||
}
|
||||
} else {
|
||||
if ack == nil {
|
||||
message = "5\(datas)-/\(nsp!),[\"\(event)\""
|
||||
} else {
|
||||
message = "5\(datas)-/\(nsp!),\(ack!)[\"\(event)\""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return self.completeMessage(message, args: args)
|
||||
}
|
||||
|
||||
class func createAck(ack:Int, withArgs args:[AnyObject], withAckType ackType:Int,
|
||||
withNsp nsp:String, withBinary binary:Int = 0) -> String {
|
||||
var msg:String
|
||||
|
||||
if ackType == 3 {
|
||||
if nsp == "/" {
|
||||
msg = "3\(ack)["
|
||||
} else {
|
||||
msg = "3/\(nsp),\(ack)["
|
||||
}
|
||||
} else {
|
||||
if nsp == "/" {
|
||||
msg = "6\(binary)-\(ack)["
|
||||
} else {
|
||||
msg = "6\(binary)-/\(nsp),\(ack)["
|
||||
}
|
||||
}
|
||||
|
||||
return self.completeMessage(msg, args: args, ack: true)
|
||||
}
|
||||
|
||||
private class func completeMessage(var message:String, args:[AnyObject], ack:Bool = false) -> String {
|
||||
var err:NSError?
|
||||
|
||||
if args.count == 0 {
|
||||
return message + "]"
|
||||
} else if !ack {
|
||||
message += ","
|
||||
}
|
||||
|
||||
for arg in args {
|
||||
|
||||
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
|
||||
message += ","
|
||||
continue
|
||||
}
|
||||
|
||||
if arg is String {
|
||||
message += "\"\(arg)\""
|
||||
message += ","
|
||||
continue
|
||||
}
|
||||
|
||||
message += "\(arg)"
|
||||
message += ","
|
||||
}
|
||||
|
||||
if message != "" {
|
||||
message.removeAtIndex(message.endIndex.predecessor())
|
||||
}
|
||||
|
||||
return message + "]"
|
||||
}
|
||||
|
||||
private func fillInArray(arr:NSArray) -> NSArray {
|
||||
var newArr = [AnyObject](count: arr.count, repeatedValue: 0)
|
||||
// println(arr)
|
||||
|
||||
for i in 0..<arr.count {
|
||||
if let nest = arr[i] as? NSArray {
|
||||
newArr[i] = self.fillInArray(nest)
|
||||
} else if let dict = arr[i] as? NSDictionary {
|
||||
newArr[i] = self.fillInDict(dict)
|
||||
} else if let str = arr[i] as? String {
|
||||
let mut = RegexMutable(str)
|
||||
if let num = mut["~~(\\d)"].groups() {
|
||||
newArr[i] = self.datas[num[1].toInt()!]
|
||||
} else {
|
||||
newArr[i] = arr[i]
|
||||
}
|
||||
} else {
|
||||
newArr[i] = arr[i]
|
||||
}
|
||||
}
|
||||
|
||||
return newArr
|
||||
}
|
||||
|
||||
private func fillInDict(dict:NSDictionary) -> NSDictionary {
|
||||
var newDict = [String: AnyObject]()
|
||||
|
||||
for (key, value) in dict {
|
||||
newDict[key as String] = value
|
||||
|
||||
// If the value is a string we need to check
|
||||
// if it is a placeholder for data
|
||||
if let str = value as? String {
|
||||
let mut = RegexMutable(str)
|
||||
|
||||
if let num = mut["~~(\\d)"].groups() {
|
||||
newDict[key as String] = self.datas[num[1].toInt()!]
|
||||
} else {
|
||||
newDict[key as String] = str
|
||||
}
|
||||
} else if let nestDict = value as? NSDictionary {
|
||||
newDict[key as String] = self.fillInDict(nestDict)
|
||||
} else if let arr = value as? NSArray {
|
||||
newDict[key as String] = self.fillInArray(arr)
|
||||
}
|
||||
}
|
||||
|
||||
return newDict
|
||||
}
|
||||
|
||||
func fillInPlaceholders(_ args:AnyObject = true) -> AnyObject {
|
||||
if let dict = args as? NSDictionary {
|
||||
return self.fillInDict(dict)
|
||||
} else if let arr = args as? NSArray {
|
||||
return self.fillInArray(args as NSArray)
|
||||
} else if let string = args as? String {
|
||||
if string == "~~\(self.currentPlace)" {
|
||||
return self.datas[0]
|
||||
}
|
||||
} else if args is Bool {
|
||||
// We have multiple items
|
||||
// Do it live
|
||||
let argsAsArray = "[\(self.args)]"
|
||||
if let parsedArr = SocketIOClient.parseData(argsAsArray) as? NSArray {
|
||||
var returnArr = [AnyObject](count: parsedArr.count, repeatedValue: 0)
|
||||
|
||||
for i in 0..<parsedArr.count {
|
||||
if let str = parsedArr[i] as? String {
|
||||
let mut = RegexMutable(str)
|
||||
|
||||
if let num = mut["~~(\\d)"].groups() {
|
||||
returnArr[i] = self.datas[num[1].toInt()!]
|
||||
} else {
|
||||
returnArr[i] = str
|
||||
}
|
||||
} else if let arr = parsedArr[i] as? NSArray {
|
||||
returnArr[i] = self.fillInArray(arr)
|
||||
} else if let dict = parsedArr[i] as? NSDictionary {
|
||||
returnArr[i] = self.fillInDict(dict)
|
||||
} else {
|
||||
returnArr[i] = parsedArr[i]
|
||||
}
|
||||
}
|
||||
return returnArr
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -25,15 +25,12 @@
|
||||
import Foundation
|
||||
|
||||
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
|
||||
public typealias AnyHandler = (event:String, items:AnyObject?)
|
||||
public typealias AckEmitter = (AnyObject...) -> Void
|
||||
|
||||
private func emitAckCallback(socket:SocketIOClient, num:Int, type:Int) -> AckEmitter {
|
||||
func emitter(items:AnyObject...) {
|
||||
socket.emitAck(num, withData: items, withAckType: type)
|
||||
}
|
||||
|
||||
return emitter
|
||||
private func emitAckCallback(socket:SocketIOClient, num:Int)
|
||||
// Curried
|
||||
(items:AnyObject...) -> Void {
|
||||
socket.emitAck(num, withData: items)
|
||||
}
|
||||
|
||||
class SocketEventHandler {
|
||||
@@ -48,7 +45,7 @@ class SocketEventHandler {
|
||||
func executeCallback(_ items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
|
||||
withSocket socket:SocketIOClient? = nil) {
|
||||
dispatch_async(dispatch_get_main_queue()) {[weak self] in
|
||||
self?.callback?(items, ack != nil ? emitAckCallback(socket!, ack!, type!) : nil)
|
||||
self?.callback?(items, ack != nil ? emitAckCallback(socket!, ack!) : nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//
|
||||
// SocketFixUTF8.swift
|
||||
// Socket.IO-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(inout name:String) {
|
||||
let utf8 = name.dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false)!
|
||||
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
|
||||
}
|
||||
+281
-631
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,237 @@
|
||||
//
|
||||
// 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
|
||||
|
||||
enum SocketPacketType: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() {
|
||||
self = SocketPacketType(rawValue: int)!
|
||||
} else {
|
||||
self = SocketPacketType(rawValue: 4)!
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SocketPacket {
|
||||
var binary = ContiguousArray<NSData>()
|
||||
var currentPlace = 0
|
||||
var data:[AnyObject]?
|
||||
var id:Int?
|
||||
var justAck = false
|
||||
var nsp = ""
|
||||
var placeholders:Int?
|
||||
var type:SocketPacketType?
|
||||
|
||||
init(type:SocketPacketType?, 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 {
|
||||
return data?.removeAtIndex(0) as! String
|
||||
}
|
||||
|
||||
func addData(data:NSData) -> Bool {
|
||||
func checkDoEvent() -> Bool {
|
||||
if self.placeholders == self.currentPlace {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if checkDoEvent() {
|
||||
return true
|
||||
}
|
||||
|
||||
self.binary.append(data)
|
||||
self.currentPlace++
|
||||
|
||||
if checkDoEvent() {
|
||||
self.currentPlace = 0
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func createMessageForEvent(event:String) -> String {
|
||||
var message:String
|
||||
var jsonSendError:NSError?
|
||||
|
||||
if self.binary.count == 0 {
|
||||
self.type = SocketPacketType.EVENT
|
||||
|
||||
if self.nsp == "/" {
|
||||
if self.id == nil {
|
||||
message = "2[\"\(event)\""
|
||||
} else {
|
||||
message = "2\(self.id!)[\"\(event)\""
|
||||
}
|
||||
} else {
|
||||
if self.id == nil {
|
||||
message = "2/\(self.nsp),[\"\(event)\""
|
||||
} else {
|
||||
message = "2/\(self.nsp),\(self.id!)[\"\(event)\""
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.type = SocketPacketType.BINARY_EVENT
|
||||
|
||||
if self.nsp == "/" {
|
||||
if self.id == nil {
|
||||
message = "5\(self.binary.count)-[\"\(event)\""
|
||||
} else {
|
||||
message = "5\(self.binary.count)-\(self.id!)[\"\(event)\""
|
||||
}
|
||||
} else {
|
||||
if self.id == nil {
|
||||
message = "5\(self.binary.count)-/\(self.nsp),[\"\(event)\""
|
||||
} else {
|
||||
message = "5\(self.binary.count)-/\(self.nsp),\(self.id!)[\"\(event)\""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return self.completeMessage(message)
|
||||
}
|
||||
|
||||
func createAck() -> String {
|
||||
var msg:String
|
||||
|
||||
if self.binary.count == 0 {
|
||||
self.type = SocketPacketType.ACK
|
||||
|
||||
if nsp == "/" {
|
||||
msg = "3\(self.id!)["
|
||||
} else {
|
||||
msg = "3/\(self.nsp),\(self.id!)["
|
||||
}
|
||||
} else {
|
||||
self.type = SocketPacketType.BINARY_ACK
|
||||
|
||||
if nsp == "/" {
|
||||
msg = "6\(self.binary.count)-\(self.id!)["
|
||||
} else {
|
||||
msg = "6\(self.binary.count)-/\(self.nsp),\(self.id!)["
|
||||
}
|
||||
}
|
||||
|
||||
return self.completeMessage(msg, ack: true)
|
||||
}
|
||||
|
||||
func completeMessage(var message:String, ack:Bool = false) -> String {
|
||||
var err:NSError?
|
||||
|
||||
if self.data == nil || self.data!.count == 0 {
|
||||
return message + "]"
|
||||
} else if !ack {
|
||||
message += ","
|
||||
}
|
||||
|
||||
for arg in self.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
|
||||
message += ","
|
||||
continue
|
||||
}
|
||||
|
||||
if arg is String {
|
||||
message += "\"\(arg)\""
|
||||
message += ","
|
||||
continue
|
||||
}
|
||||
|
||||
message += "\(arg)"
|
||||
message += ","
|
||||
}
|
||||
|
||||
if message != "" {
|
||||
message.removeAtIndex(message.endIndex.predecessor())
|
||||
}
|
||||
|
||||
return message + "]"
|
||||
}
|
||||
|
||||
func fillInPlaceholders() {
|
||||
var newArr = NSMutableArray(array: self.data!)
|
||||
|
||||
for i in 0..<self.data!.count {
|
||||
if let str = self.data?[i] as? String {
|
||||
if let num = str["~~(\\d)"].groups() {
|
||||
newArr[i] = self.binary[num[1].toInt()!]
|
||||
}
|
||||
} else if self.data?[i] is NSDictionary || self.data?[i] is NSArray {
|
||||
newArr[i] = self._fillInPlaceholders(self.data![i])
|
||||
}
|
||||
}
|
||||
|
||||
self.data = newArr as [AnyObject]
|
||||
}
|
||||
|
||||
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
|
||||
if let str = data as? String {
|
||||
if let num = str["~~(\\d)"].groups() {
|
||||
return self.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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
//
|
||||
// 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 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
|
||||
class func parseString(str:String) -> SocketPacket? {
|
||||
let arr = Array(str)
|
||||
let type = String(arr[0])
|
||||
|
||||
if arr.count == 1 {
|
||||
return SocketPacket(type: SocketPacketType(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 buf.toInt() == nil || arr[i] != "-" {
|
||||
NSLog("Error parsing \(str)")
|
||||
return nil
|
||||
} else {
|
||||
placeholders = buf.toInt()!
|
||||
}
|
||||
}
|
||||
|
||||
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: SocketPacketType(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 + 1 < arr.count {
|
||||
let d = String(arr[++i...arr.count-1])
|
||||
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
|
||||
|
||||
let data = SocketParser.parseData(noPlaceholders) as! [AnyObject]
|
||||
|
||||
return SocketPacket(type: SocketPacketType(str: type), data: data,
|
||||
nsp: nsp, placeholders: placeholders, id: id)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Parses data for events
|
||||
class func parseData(data:String) -> AnyObject? {
|
||||
var err:NSError?
|
||||
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
||||
let parsed:AnyObject? = NSJSONSerialization.JSONObjectWithData(stringData!,
|
||||
options: NSJSONReadingOptions.AllowFragments, error: &err)
|
||||
|
||||
if err != nil {
|
||||
// println(err)
|
||||
return nil
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
|
||||
class func parseForEmit(packet:SocketPacket) {
|
||||
shredder.deconstructPacket(packet)
|
||||
}
|
||||
|
||||
// Parses messages recieved
|
||||
class func parseSocketMessage(stringMessage:String, socket:SocketIOClient) {
|
||||
if stringMessage == "" {
|
||||
return
|
||||
}
|
||||
|
||||
func checkNSP(nsp:String) -> Bool {
|
||||
if nsp == "" && socket.nsp != "/" {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
let p = parseString(stringMessage) as SocketPacket!
|
||||
|
||||
if p.type == SocketPacketType.EVENT {
|
||||
if checkNSP(p.nsp) {
|
||||
return
|
||||
}
|
||||
|
||||
socket.handleEvent(p.getEvent(), data: p.data,
|
||||
isInternalMessage: false, wantsAck: p.id)
|
||||
} else if p.type == SocketPacketType.ACK {
|
||||
if checkNSP(p.nsp) {
|
||||
return
|
||||
}
|
||||
|
||||
socket.handleAck(p.id!, data: p.data)
|
||||
} else if p.type == SocketPacketType.BINARY_EVENT {
|
||||
if checkNSP(p.nsp) {
|
||||
return
|
||||
}
|
||||
|
||||
socket.waitingData.append(p)
|
||||
} else if p.type == SocketPacketType.BINARY_ACK {
|
||||
if checkNSP(p.nsp) {
|
||||
return
|
||||
}
|
||||
|
||||
p.justAck = true
|
||||
socket.waitingData.append(p)
|
||||
} else if p.type == SocketPacketType.CONNECT {
|
||||
if p.nsp == "" && socket.nsp != "/" {
|
||||
socket.joinNamespace()
|
||||
} else if p.nsp != "" && socket.nsp == "/" {
|
||||
socket.didConnect()
|
||||
} else {
|
||||
socket.didConnect()
|
||||
}
|
||||
} else if p.type == SocketPacketType.DISCONNECT {
|
||||
socket.didForceClose("Got Disconnect")
|
||||
}
|
||||
}
|
||||
|
||||
// Handles binary data
|
||||
class func parseBinaryData(data:NSData, socket:SocketIOClient) {
|
||||
// NSLog(data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros))
|
||||
|
||||
if socket.waitingData.count == 0 {
|
||||
NSLog("Got data when not remaking packet")
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
+80
-200
@@ -16,11 +16,10 @@ import Foundation
|
||||
var swiftRegexCache = [String: NSRegularExpression]()
|
||||
|
||||
public class SwiftRegex: NSObject, BooleanType {
|
||||
|
||||
var target: NSString
|
||||
var target:String
|
||||
var regex: NSRegularExpression
|
||||
|
||||
init(target:NSString, pattern:String, options:NSRegularExpressionOptions = nil) {
|
||||
|
||||
init(target:String, pattern:String, options:NSRegularExpressionOptions = nil) {
|
||||
self.target = target
|
||||
if let regex = swiftRegexCache[pattern] {
|
||||
self.regex = regex
|
||||
@@ -37,45 +36,45 @@ public class SwiftRegex: NSObject, BooleanType {
|
||||
}
|
||||
super.init()
|
||||
}
|
||||
|
||||
|
||||
class func failure(message: String) {
|
||||
println("SwiftRegex: "+message)
|
||||
//assert(false,"SwiftRegex: failed")
|
||||
}
|
||||
|
||||
|
||||
final var targetRange: NSRange {
|
||||
return NSRange(location: 0,length: target.length)
|
||||
return NSRange(location: 0,length: count(target.utf16))
|
||||
}
|
||||
|
||||
final func substring(range: NSRange) -> NSString! {
|
||||
|
||||
final func substring(range: NSRange) -> String? {
|
||||
if ( range.location != NSNotFound ) {
|
||||
return target.substringWithRange(range)
|
||||
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)) as String
|
||||
|
||||
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) )
|
||||
|
||||
public func groups(options: NSMatchingOptions = nil) -> [String]? {
|
||||
return groupsForMatch(regex.firstMatchInString(target as String, options: options, range: targetRange))
|
||||
}
|
||||
|
||||
func groupsForMatch(match: NSTextCheckingResult!) -> [String]! {
|
||||
|
||||
func groupsForMatch(match: NSTextCheckingResult!) -> [String]? {
|
||||
if match != nil {
|
||||
var groups = [String]()
|
||||
for groupno in 0...regex.numberOfCaptureGroups {
|
||||
if let group = substring(match.rangeAtIndex(groupno)) as String! {
|
||||
if let group = substring(match.rangeAtIndex(groupno)) {
|
||||
groups += [group]
|
||||
} else {
|
||||
groups += ["_"] // avoids bridging problems
|
||||
@@ -86,122 +85,83 @@ public class SwiftRegex: NSObject, BooleanType {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
public subscript(groupno: Int) -> String! {
|
||||
|
||||
public subscript(groupno: Int) -> String? {
|
||||
get {
|
||||
return groups()[groupno]
|
||||
return groups()?[groupno]
|
||||
}
|
||||
|
||||
set(newValue) {
|
||||
if let mutableTarget = target as? NSMutableString {
|
||||
for match in matchResults()!.reverse() {
|
||||
let replacement = regex.replacementStringForResult( match,
|
||||
inString: target as String, offset: 0, template: newValue )
|
||||
mutableTarget.replaceCharactersInRange(match.rangeAtIndex(groupno), withString: replacement)
|
||||
}
|
||||
} else {
|
||||
SwiftRegex.failure("Group modify on non-mutable")
|
||||
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) as 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 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)) as String] =
|
||||
substring(match.rangeAtIndex(2))
|
||||
out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))!
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func substituteMatches(substitution: (NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String,
|
||||
options:NSMatchingOptions = nil) -> NSMutableString {
|
||||
|
||||
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) ) as String )
|
||||
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) ) as String )
|
||||
|
||||
if let mutableTarget = target as? NSMutableString {
|
||||
mutableTarget.setString(out as String)
|
||||
return mutableTarget
|
||||
} else {
|
||||
SwiftRegex.failure("Modify on non-mutable")
|
||||
return out
|
||||
}
|
||||
|
||||
out.appendString(substring( NSRange(location:pos, length:targetRange.length-pos))!)
|
||||
|
||||
return out as String
|
||||
}
|
||||
/* removed Beta6
|
||||
public func __conversion() -> Bool {
|
||||
return doesMatch()
|
||||
}
|
||||
|
||||
public func __conversion() -> NSRange {
|
||||
return range()
|
||||
}
|
||||
|
||||
public func __conversion() -> String {
|
||||
return match()
|
||||
}
|
||||
|
||||
public func __conversion() -> [String] {
|
||||
return matches()
|
||||
}
|
||||
|
||||
public func __conversion() -> [[String]] {
|
||||
return allGroups()
|
||||
}
|
||||
|
||||
public func __conversion() -> [String:String] {
|
||||
return dictionary()
|
||||
}
|
||||
*/
|
||||
|
||||
public var boolValue: Bool {
|
||||
return doesMatch()
|
||||
}
|
||||
}
|
||||
|
||||
extension NSString {
|
||||
public subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex {
|
||||
return SwiftRegex(target: self, pattern: pattern, options: options)
|
||||
}
|
||||
}
|
||||
|
||||
extension NSString {
|
||||
public subscript(pattern: String) -> SwiftRegex {
|
||||
return SwiftRegex(target: self, pattern: pattern)
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
public subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex {
|
||||
return SwiftRegex(target: self, pattern: pattern, options: options)
|
||||
@@ -214,116 +174,36 @@ extension String {
|
||||
}
|
||||
}
|
||||
|
||||
public func RegexMutable(string: NSString) -> NSMutableString {
|
||||
return NSMutableString(string:string as String)
|
||||
}
|
||||
|
||||
public func ~= (left: SwiftRegex, right: String) -> NSMutableString {
|
||||
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]) -> NSMutableString {
|
||||
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) -> NSMutableString {
|
||||
// return right(left.substring(match.range))
|
||||
return left.substituteMatches(
|
||||
{match, stop -> String in
|
||||
right(left.substring(match.range) as String)
|
||||
}, options: nil)
|
||||
}
|
||||
|
||||
public func ~= (left: SwiftRegex, right: ([String]) -> String) -> NSMutableString {
|
||||
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)
|
||||
}
|
||||
|
||||
// my take on custom threading operators from
|
||||
// http://ijoshsmith.com/2014/07/05/custom-threading-operator-in-swift/
|
||||
|
||||
private let _queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
|
||||
|
||||
public func | (left: () -> Void, right: () -> Void) {
|
||||
dispatch_async(_queue) {
|
||||
left()
|
||||
dispatch_async(dispatch_get_main_queue(), right)
|
||||
}
|
||||
}
|
||||
|
||||
public func | <R> (left: () -> R, right: (result:R) -> Void) {
|
||||
dispatch_async(_queue) {
|
||||
let result = left()
|
||||
dispatch_async(dispatch_get_main_queue(), {
|
||||
right(result:result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// dispatch groups { block } & { block } | { completion }
|
||||
public func & (left: () -> Void, right: () -> Void) -> [() -> Void] {
|
||||
return [left, right];
|
||||
}
|
||||
|
||||
public func & (left: [() -> Void], right: () -> Void) -> [() -> Void] {
|
||||
var out = left
|
||||
out.append( right )
|
||||
return out
|
||||
}
|
||||
|
||||
public func | (left: [() -> Void], right: () -> Void) {
|
||||
let group = dispatch_group_create()
|
||||
|
||||
for block in left {
|
||||
dispatch_group_async(group, _queue, block)
|
||||
}
|
||||
|
||||
dispatch_group_notify(group, dispatch_get_main_queue(), right)
|
||||
}
|
||||
|
||||
// parallel blocks with returns
|
||||
public func & <R> (left: () -> R, right: () -> R) -> [() -> R] {
|
||||
return [left, right]
|
||||
}
|
||||
|
||||
public func & <R> (left: [() -> R], right: () -> R) -> [() -> R] {
|
||||
var out = left
|
||||
out.append( right )
|
||||
return out
|
||||
}
|
||||
|
||||
public func | <R> (left: [() -> R], right: (results:[R!]) -> Void) {
|
||||
let group = dispatch_group_create()
|
||||
|
||||
var results = Array<R!>()
|
||||
for t in 0..<left.count {
|
||||
results += [nil]
|
||||
}
|
||||
|
||||
for t in 0..<left.count {
|
||||
//dispatch_retain(group)
|
||||
dispatch_group_enter(group)
|
||||
dispatch_async(_queue, {
|
||||
results[t] = left[t]()
|
||||
dispatch_group_leave(group)
|
||||
//dispatch_release(group)
|
||||
})
|
||||
}
|
||||
|
||||
dispatch_group_notify(group, dispatch_get_main_queue(), {
|
||||
right(results: results)
|
||||
})
|
||||
}, options: nil)
|
||||
}
|
||||
+13
-14
@@ -7,7 +7,6 @@
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
import Foundation
|
||||
import CoreFoundation
|
||||
|
||||
public protocol WebSocketDelegate: class {
|
||||
func websocketDidConnect(socket: WebSocket)
|
||||
@@ -236,8 +235,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
if self.selfSignedSSL {
|
||||
let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
|
||||
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings)
|
||||
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings)
|
||||
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||
}
|
||||
isRunLoop = true
|
||||
inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
@@ -247,18 +246,18 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let bytes = UnsafePointer<UInt8>(data.bytes)
|
||||
outputStream!.write(bytes, maxLength: data.length)
|
||||
while(isRunLoop) {
|
||||
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as NSDate)
|
||||
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as! NSDate)
|
||||
}
|
||||
}
|
||||
//delegate for the stream methods. Processes incoming bytes
|
||||
func stream(aStream: NSStream!, handleEvent eventCode: NSStreamEvent) {
|
||||
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
|
||||
|
||||
if eventCode == .HasBytesAvailable {
|
||||
if(aStream == inputStream) {
|
||||
processInputStream()
|
||||
}
|
||||
} else if eventCode == .ErrorOccurred {
|
||||
disconnectStream(aStream!.streamError)
|
||||
disconnectStream(aStream.streamError)
|
||||
} else if eventCode == .EndEncountered {
|
||||
disconnectStream(nil)
|
||||
}
|
||||
@@ -333,7 +332,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
|
||||
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
|
||||
let CRLFBytes = [UInt8("\r"), UInt8("\n"), UInt8("\r"), UInt8("\n")]
|
||||
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
|
||||
var k = 0
|
||||
var totalSize = 0
|
||||
for var i = 0; i < bufferLen; i++ {
|
||||
@@ -376,7 +375,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response.takeUnretainedValue())
|
||||
let headers: NSDictionary = cfHeaders.takeUnretainedValue()
|
||||
let acceptKey = headers[headerWSAcceptName] as NSString
|
||||
let acceptKey = headers[headerWSAcceptName] as! NSString
|
||||
if acceptKey.length > 0 {
|
||||
return true
|
||||
}
|
||||
@@ -500,7 +499,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
|
||||
}
|
||||
if receivedOpcode == OpCode.Pong.rawValue {
|
||||
let step = Int(offset+len)
|
||||
let step = offset + Int(len)
|
||||
let extra = bufferLen-step
|
||||
if extra > 0 {
|
||||
processRawMessage((buffer+step), bufferLen: extra)
|
||||
@@ -565,7 +564,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
processResponse(response!)
|
||||
}
|
||||
|
||||
let step = Int(offset+len)
|
||||
let step = offset + Int(len)
|
||||
let extra = bufferLen-step
|
||||
if(extra > 0) {
|
||||
processExtra((buffer+step), bufferLen: extra)
|
||||
@@ -597,9 +596,9 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
dispatch_async(queue,{
|
||||
if let textBlock = self.receivedTextBlock{
|
||||
textBlock(str!)
|
||||
textBlock(str! as String)
|
||||
}
|
||||
self.delegate?.websocketDidReceiveMessage(self, text: str!)
|
||||
self.delegate?.websocketDidReceiveMessage(self, text: str! as String)
|
||||
})
|
||||
} else if response.code == .BinaryFrame {
|
||||
let data = response.buffer! //local copy so it is perverse for writing
|
||||
@@ -673,7 +672,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
buffer[1] |= self.MaskMask
|
||||
var maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
|
||||
SecRandomCopyBytes(kSecRandomDefault, UInt(sizeof(UInt32)), maskKey)
|
||||
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
|
||||
offset += sizeof(UInt32)
|
||||
|
||||
for (var i = 0; i < dataLength; i++) {
|
||||
@@ -711,4 +710,4 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user