Compare commits

...
40 Commits
Author SHA1 Message Date
Erik 472ba50058 bump version 2015-03-18 09:15:13 -04:00
Erik ac31b4a788 hopefully fix nuclearace/Socket.IO-Client-Swift#27 2015-03-17 12:12:30 -04:00
Erik 7d08f962d5 fix socketio/socket.io-client-swift#16 2015-03-16 20:49:02 -04:00
Erik 2712461044 fix #26 2015-03-16 17:58:12 -04:00
Erik 44e2781076 #11 2015-03-16 13:24:25 -04:00
Erik fea16879e1 Receive doubly encoded utf8 in polling until https://github.com/Automattic/engine.io/issues/315 is fixed properly 2015-03-16 13:12:37 -04:00
Erik Little e932d0a26b Fix copypasta 2015-03-16 11:53:14 -04:00
Erik 6e84950c05 API changed, change version 2015-03-16 11:49:10 -04:00
Erik 90187aa458 fix convenience constructor. Bump version 2015-03-16 11:47:42 -04:00
Erik 68da96f37d fix for objc 2015-03-16 09:23:21 -04:00
Erik ffd92d7bb4 Merge branch 'timeouts' 2015-03-16 09:22:32 -04:00
Erik c103734035 work on parsing stuff 2015-03-15 23:41:01 -04:00
Erik 2022f282c9 add no timeout 2015-03-14 19:46:03 -04:00
Erik d75457f397 Merge branch 'master' into timeouts 2015-03-14 19:12:09 -04:00
Erik bb6bd2b4ca fix race condition in polling 2015-03-14 19:09:54 -04:00
Erik c177671112 work on #23 2015-03-14 14:11:32 -04:00
Erik 2cc68aead6 Don't poll on sendPollMessage 2015-03-13 09:51:53 -04:00
Erik 1f05bde09b small tweaks 2015-03-13 09:09:37 -04:00
Erik 5b019a91c5 start refactoring 2015-03-12 17:54:17 -04:00
Erik a28e924b04 forgot one 2015-03-12 16:53:11 -04:00
Erik f7bf9d4e6b bump version 2015-03-12 16:34:36 -04:00
Erik 37537de213 change visibility of socketioclient members 2015-03-12 16:34:08 -04:00
Erik 8e7c8444d3 set socket sid 2015-03-12 13:44:55 -04:00
Erik 74939f1cea fixes 2015-03-12 13:38:06 -04:00
Erik ab5cccce85 fix binary in dictionaries 2015-03-12 11:38:45 -04:00
Erik 58362f6352 clean up readme 2015-03-12 10:27:37 -04:00
Erik abbd8e6a67 update 2015-03-12 10:19:59 -04:00
Erik Little 3ba793acf1 Merge pull request #8 from banjun/readme-cocoapods
[README] add CocoaPods in Installation section
2015-03-12 10:19:27 -04:00
banjun ea20dc809e [README] add CocoaPods in Installation section 2015-03-12 22:58:00 +09:00
Erik 3e5fe4009c Really update it 2015-03-12 09:33:59 -04:00
Erik a84aa31489 update podspec 2015-03-12 09:32:12 -04:00
Erik 8f7f43f83e add osx 2015-03-12 09:31:27 -04:00
Erik 30cd0bd6cd update thing 2015-03-12 09:17:49 -04:00
Erik Little ac2bc13b11 Merge pull request #7 from banjun/cocoapods
CocoaPods podspec for v1.1.0
2015-03-12 09:08:17 -04:00
banjun 33f3ef4846 add podspec for v1.1.0 and LICENSE 2015-03-12 19:59:49 +09:00
Erik 2e451e5185 trim more 2015-03-11 18:05:25 -04:00
Erik 114ce4ca0f trim example 2015-03-11 17:42:51 -04:00
Erik 8c02f5ef7b update readme with new methods 2015-03-11 17:38:27 -04:00
Erik 711ce8d8c4 fixes. add better objective-c support 2015-03-11 17:33:21 -04:00
Erik 8365ded215 Use starscream for websockets. Execute emitAcks on the main queue. 2015-03-11 13:33:54 -04:00
12 changed files with 1878 additions and 887 deletions

No files matched your search

+230
View File
@@ -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.
+59 -69
View File
@@ -7,24 +7,53 @@ For Swift 1.2 use the 1.2 branch.
Installation
============
1. Requires linking [SocketRocket](https://github.com/square/SocketRocket) against your xcode project. (Be sure to link the [frameworks](https://github.com/square/SocketRocket#framework-dependencies) required by SocketRocket)
2. Create a bridging header for SocketRocket
3. Copy the SwiftIO folder into your xcode project
Manually (iOS 7+)
-----------------
1. Copy the SwiftIO folder into your Xcode project!
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.1'
```
Install pods:
```
$ pod install
```
Import in your swift file:
```swift
import Socket_IO_Client_Swift
```
API
===
Constructor
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. See example)
`convenience init(socketURL: String, options:NSDictionary?)` - Same as above, but meant for Objective-C. See Objective-C Example.
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.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.
5. `socket.connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
6. `socket.connectWithParams(params:[String: AnyObject])` - Establishes a connection to the server passing the specified params. A "connect" event is fired upon successful connection.
7. `socket.close()` - Closes the socket. Once a socket is closed it should not be reopened.
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.
Events
------
@@ -71,81 +100,42 @@ socket.on("ackEvent") {data, ack in
println("Got ackEvent")
}
socket.emitWithAck("ackTest", "test").onAck {data in
// data is an array
if let int = data?[1] as? Int {
println("Got int")
}
// You can specify a custom timeout interval. 0 means no timeout.
socket.emitWithAck("ackTest", "test").onAck(0) {data in
println(data?[0])
}
ack?("Got your event", "dude")
}
socket.on("disconnect") {data, ack in
if let reason = data?[0] as? String {
println("Socket disconnected: \(reason)")
}
}
socket.on("reconnect") {data, ack in
if let reason = data?[0] as? String {
println("Socket reconnecting: \(reason)")
}
}
socket.on("reconnectAttempt") {data, ack in
if let triesLeft = data?[0] as? Int {
println(triesLeft)
}
}
// End Socket Events
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"])
}
}
// Recieving binary
socket.on("dataTest") {data, ack in
if let data = data?[0] as? NSData {
println("data is binary")
}
}
socket.on("objectDataTest") {data, ack in
if let dict = data?[0] as? NSDictionary {
if let data = dict["data"] as? NSData {
let string = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Got data: \(string!)")
}
}
}
// Connecting
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" :@[@"echo test"]];
[[socket emitWithAckObjc:@"ackack" :@[@"test"]] onAck:0 withCallback:^(NSArray* data) {
NSLog(@"Got data");
}];
}];
// Sending binary
socket.emit("testData", [
"data": "Hello World".dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)!,
"test": true])
```
Detailed Example
+19
View File
@@ -0,0 +1,19 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.version = "1.2.2"
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 => 'v1.2.2' }
s.source_files = "SwiftIO/**/*.swift"
s.requires_arc = true
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
end
+31 -4
View File
@@ -24,19 +24,46 @@
import Foundation
typealias AckCallback = (NSArray?) -> Void
public typealias AckCallback = (NSArray?) -> Void
class SocketAckHandler {
@objc public class SocketAckHandler {
let ackNum:Int!
let event:String!
var acked = false
var callback:AckCallback?
weak var socket:SocketIOClient?
init(event:String, ackNum:Int = 0) {
init(event:String, ackNum:Int = 0, socket:SocketIOClient) {
self.ackNum = ackNum
self.event = event
self.socket = socket
}
func onAck(callback:AckCallback) {
public func onAck(timeout:UInt64, withCallback callback:AckCallback) {
self.callback = callback
if timeout != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {[weak self] in
if self == nil {
return
}
if !self!.acked {
self?.executeAck(["No ACK"])
self?.socket?.removeAck(self!)
}
}
}
}
func executeAck(data:NSArray?) {
dispatch_async(dispatch_get_main_queue()) {[weak self, cb = self.callback] in
self?.acked = true
cb?(data)
return
}
}
}
+113 -122
View File
@@ -24,10 +24,6 @@
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)
@@ -46,7 +42,7 @@ private enum PacketType: String {
case NOOP = "6"
}
class SocketEngine: NSObject, SRWebSocketDelegate {
public class SocketEngine: NSObject, WebSocketDelegate {
unowned let client:SocketIOClient
private let workQueue = NSOperationQueue()
private let emitQueue = dispatch_queue_create(
@@ -55,18 +51,22 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
"parseQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
private let handleQueue = dispatch_queue_create(
"handleQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
private let session:NSURLSession!
private var _connected = false
private var fastUpgrade = false
private var forcePolling = 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 waitingForPoll = false
private var waitingForPost = false
private var _websocket = false
private var websocketConnected = false
var connected = false
var connected:Bool {
return self._connected
}
var pingInterval:Int?
var polling:Bool {
return self._polling
@@ -77,7 +77,7 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
var websocket:Bool {
return self._websocket
}
var ws:SRWebSocket?
var ws:WebSocket?
init(client:SocketIOClient, forcePolling:Bool = false) {
self.client = client
@@ -142,13 +142,29 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
return (urlPolling, urlWebSocket)
}
private func doFastUpgrade() {
self.sendWebSocketMessage("", withType: PacketType.UPGRADE)
self._websocket = true
self._polling = false
self.fastUpgrade = false
self.flushProbeWait()
}
private func doPoll() {
if self.urlPolling == nil || self.websocket || self.waitingForPoll || !self.connected {
if self.websocket || self.waitingForPoll || !self.connected {
return
}
self.waitingForPoll = true
self.doRequest(self.parsePollingMessage)
}
private func doRequest(callback:(String) -> Void) {
if !self.polling {
return
}
let req = NSURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
self.waitingForPoll = true
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
if self == nil {
@@ -157,22 +173,24 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
if self!.polling {
self?.handlePollingFailed(err)
}
return
}
// println(data)
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
// println(str)
dispatch_async(self?.parseQueue) {[weak self] in
self?.parsePollingMessage(str)
return
}
dispatch_async(self!.parseQueue) {callback(str)}
}
self?.waitingForPoll = false
self?.doPoll()
if self!.fastUpgrade {
self?.doFastUpgrade()
return
} else {
self?.doPoll()
}
}.resume()
}
@@ -212,24 +230,21 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
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")
// NSLog("posting: \(postStr)")
req.HTTPBody = postData
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
self.waitingForPost = true
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
if err != nil {
if self!.polling {
self?.handlePollingFailed(err)
}
if self == nil {
return
} else if self == nil {
} else if err != nil && self!.polling {
self?.handlePollingFailed(err)
return
}
@@ -245,18 +260,19 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
// Send them raw
private func flushWaitingForPostToWebSocket() {
for msg in self.postWait {
self.ws?.send(msg)
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?) {
assert(self.polling, "Polling failed when we're not polling")
if !self.client.reconnecting {
self.connected = false
self.ws?.close()
self._connected = false
self.ws?.disconnect()
self.pingTimer?.invalidate()
self.waitingForPoll = false
self.waitingForPost = false
@@ -265,12 +281,11 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
}
func open(opts:[String: AnyObject]? = nil) {
if self.waitingForPost || self.waitingForPoll || self.websocket || self.connected {
if self.connected {
assert(false, "We're in a bad state, this shouldn't happen.")
}
let (urlPolling, urlWebSocket) = self.createURLs(params: opts)
self.urlPolling = urlPolling
self.urlWebSocket = urlWebSocket
let reqPolling = NSURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
@@ -284,9 +299,8 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
return
}
if let dataString = NSString(data: data, encoding: NSUTF8StringEncoding) {
var mutString = RegexMutable(dataString)
let parsed:[String]? = mutString["(\\d*):(\\d)(\\{.*\\})?"].groups()
if let dataString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
let parsed:[String]? = dataString["(\\d*):(\\d)(\\{.*\\})?"].groups()
if parsed == nil || parsed?.count != 4 {
return
@@ -301,19 +315,18 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
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
self?._connected = true
if !self!.forcePolling {
self?.ws = SRWebSocket(URL:
NSURL(string: urlWebSocket + "&sid=\(self!.sid)")!)
self?.ws = WebSocket(url: NSURL(string: urlWebSocket + "&sid=\(self!.sid)")!)
self?.ws?.queue = self?.handleQueue
self?.ws?.delegate = self
self?.ws?.open()
self?.ws?.connect()
}
} else {
NSLog("Error handshaking")
@@ -360,7 +373,7 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
length += chr
} else {
if length == "" || testLength(length, &n) {
self.handlePollingFailed(nil)
println("failure in parsePollingMessage")
return
}
@@ -376,8 +389,7 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
if msg.length != 0 {
// Be sure to capture the value of the msg
dispatch_async(self.handleQueue) {[weak self, msg] in
fixSwift = msg
self?.parseEngineMessage(fixSwift)
self?.parseEngineMessage(msg)
return
}
}
@@ -388,37 +400,37 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
}
}
private func parseEngineMessage(message:AnyObject?) {
// println(message!)
if let data = message as? NSData {
// Strip off message type
self.client.parseSocketMessage(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
return
}
var messageString = message as String
var strMessage = RegexMutable(messageString)
private func parseEngineData(data:NSData) {
self.client.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
}
private func parseEngineMessage(var message:String) {
// NSLog("Engine got message: \(message)")
fixDoubleUTF8(&message)
// We should upgrade
if strMessage == "3probe" {
if message == "3probe" {
self.upgradeTransport()
return
}
let type = strMessage["^(\\d)"].groups()?[1]
let type = message["^(\\d)"].groups()?[1]
if type != PacketType.MESSAGE.rawValue {
// TODO Handle other packets
if messageString.hasPrefix("b4") {
if message.hasPrefix("b4") {
// binary in base64 string
messageString.removeRange(Range<String.Index>(start: messageString.startIndex,
end: advance(messageString.startIndex, 2)))
message.removeRange(Range<String.Index>(start: message.startIndex,
end: advance(message.startIndex, 2)))
if let data = NSData(base64EncodedString: messageString,
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) {
// println("sending \(data)")
self.client.parseSocketMessage(data)
dispatch_async(self.client.handleQueue) {[weak self] in
self?.client.parseBinaryData(data)
return
}
}
return
@@ -427,7 +439,7 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
return
}
if messageString == PacketType.CLOSE.rawValue {
if message == PacketType.CLOSE.rawValue {
// do nothing
return
}
@@ -436,10 +448,12 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
}
// Remove message type
messageString.removeAtIndex(messageString.startIndex)
// println("sending \(messageString)")
message.removeAtIndex(message.startIndex)
self.client.parseSocketMessage(messageString)
dispatch_async(self.client.handleQueue) {[weak self] in
self?.client.parseSocketMessage(message)
return
}
}
private func probeWebSocket() {
@@ -448,7 +462,7 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
}
}
func send(msg:String, datas:[NSData]? = nil) {
public func send(msg:String, datas:[NSData]? = nil) {
let _send = {[weak self] (msg:String, datas:[NSData]?) -> () -> Void in
return {
if self == nil || !self!.connected {
@@ -486,37 +500,35 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
}
}
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!)
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 !self.waitingForPost {
self.flushWaitingForPost()
}
}
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?.send("\(type.rawValue)\(str)")
// 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?.send(data!)
self.ws?.writeData(data!)
}
}
}
@@ -537,60 +549,39 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
private func upgradeTransport() {
if self.websocketConnected {
// Do a fast upgrade
self.fastUpgrade = true
self.probing = false
self._websocket = true
self.waitingForPoll = false
self._polling = false
self.sendWebSocketMessage("", withType: PacketType.UPGRADE)
self.flushProbeWait()
self.sendPollMessage("", withType: PacketType.NOOP)
}
}
// Called when a message is recieved
func webSocket(webSocket:SRWebSocket!, didReceiveMessage message:AnyObject?) {
// println(message)
dispatch_async(self.handleQueue) {[weak self] in
self?.parseEngineMessage(message)
return
}
}
// Called when the socket is opened
func webSocketDidOpen(webSocket:SRWebSocket!) {
public func websocketDidConnect(socket:WebSocket) {
self.websocketConnected = true
self.probing = true
self.probeWebSocket()
}
// Called when the socket is closed
func webSocket(webSocket:SRWebSocket!, didCloseWithCode code:Int, reason:String!, wasClean:Bool) {
public func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
self.websocketConnected = false
self.probing = false
if self.websocket {
self.pingTimer?.invalidate()
self.connected = false
self._connected = false
self._websocket = false
self._polling = true
self.client.webSocketDidCloseWithCode(code, reason: reason, wasClean: wasClean)
self.client.webSocketDidCloseWithCode(1, reason: "Socket Disconnect", wasClean: true)
} else {
self.flushProbeWait()
}
}
// Called when an error occurs.
func webSocket(webSocket:SRWebSocket!, didFailWithError error:NSError!) {
self.websocketConnected = false
self._polling = true
self.probing = false
if self.websocket {
self.pingTimer?.invalidate()
self.connected = false
self.client.webSocketDidFailWithError(error)
} else {
self.flushProbeWait()
}
public func websocketDidReceiveMessage(socket:WebSocket, text:String) {
self.parseEngineMessage(text)
}
}
public func websocketDidReceiveData(socket:WebSocket, data:NSData) {
self.parseEngineData(data)
}
}
+4 -9
View File
@@ -173,8 +173,7 @@ class SocketEvent {
} 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() {
if let num = str["~~(\\d)"].groups() {
newArr[i] = self.datas[num[1].toInt()!]
} else {
newArr[i] = arr[i]
@@ -196,9 +195,7 @@ class SocketEvent {
// 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() {
if let num = str["~~(\\d)"].groups() {
newDict[key as String] = self.datas[num[1].toInt()!]
} else {
newDict[key as String] = str
@@ -226,14 +223,12 @@ class SocketEvent {
// We have multiple items
// Do it live
let argsAsArray = "[\(self.args)]"
if let parsedArr = SocketIOClient.parseData(argsAsArray) as? NSArray {
if let parsedArr = SocketParser.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() {
if let num = str["~~(\\d)"].groups() {
returnArr[i] = self.datas[num[1].toInt()!]
} else {
returnArr[i] = str
+5 -3
View File
@@ -22,9 +22,11 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
typealias AnyHandler = (event:String, items:AnyObject?)
typealias AckEmitter = (AnyObject...) -> Void
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...) {
+100
View File
@@ -0,0 +1,100 @@
//
// 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.
//
// Adapted from: https://github.com/durbrow/fix-double-utf8.swift
import Foundation
var memoizer = [String: UnicodeScalar]()
func lookup(base:UnicodeScalar, combi:UnicodeScalar) -> UnicodeScalar {
let combined = "\(base)\(combi)"
if let y = memoizer[combined] {
return y
}
for i in 0x80...0xFF {
let ch = UnicodeScalar(i)
if String(ch) == combined {
memoizer[combined] = ch
return ch
}
}
let ch = UnicodeScalar(0xFFFD) // Unicode replacement character �
memoizer[combined] = ch
return ch
}
func fixDoubleUTF8(inout name:String) {
var isASCII = true
var y = [UInt8]()
for ch in name.unicodeScalars {
if ch.value < 0x80 {
y.append(UInt8(ch))
continue
}
isASCII = false
if ch.value < 0x100 {
y.append(UInt8(ch))
continue
}
// might be a combining character that when combined with the
// preceeding character maps to a codepoint in the UTF8 range
if y.count == 0 {
return
}
let last = y.removeLast()
let repl = lookup(UnicodeScalar(last), ch)
// the replacement needs to be in the UTF8 range
if repl.value >= 0x100 {
return
}
y.append(UInt8(repl))
}
if isASCII {
return
}
y.append(0) // null terminator
return y.withUnsafeBufferPointer {
let cstr = UnsafePointer<CChar>($0.baseAddress) // typecase from uint8_t * to char *
let rslt = String.fromCStringRepairingIllFormedUTF8(cstr) // -> (String, Bool)
if let str = rslt.0 {
if !rslt.hadError {
name = str
}
}
return
}
}
+118 -513
View File
@@ -24,9 +24,8 @@
import Foundation
class SocketIOClient {
let engine:SocketEngine!
let socketURL:NSMutableString!
public class SocketIOClient: NSObject {
let socketURL:String!
let ackQueue = dispatch_queue_create("ackQueue".cStringUsingEncoding(NSUTF8StringEncoding),
DISPATCH_QUEUE_SERIAL)
let handleQueue = dispatch_queue_create("handleQueue".cStringUsingEncoding(NSUTF8StringEncoding),
@@ -37,38 +36,53 @@ class SocketIOClient {
private lazy var params = [String: AnyObject]()
private var ackHandlers = [SocketAckHandler]()
private var anyHandler:((AnyHandler) -> Void)?
private var currentAck = -1
private var _closed = false
private var _connected = false
private var _connecting = false
private var currentReconnectAttempt = 0
private var forcePolling = false
private var handlers = [SocketEventHandler]()
private var waitingData = [SocketEvent]()
private var paramConnect = false
private var _secure = false
private var _sid:String?
private var _reconnecting = false
private var reconnectTimer:NSTimer?
var closed = false
var connected = false
var connecting = false
var nsp:String?
var reconnects = true
var reconnecting = false
var reconnectWait = 10
var secure:Bool {
internal var currentAck = -1
internal var waitingData = [SocketEvent]()
public var closed:Bool {
return self._closed
}
public var connected:Bool {
return self._connected
}
public var connecting:Bool {
return self._connecting
}
public var engine:SocketEngine?
public var nsp:String?
public var reconnects = true
public var reconnecting:Bool {
return self._reconnecting
}
public var reconnectWait = 10
public var secure:Bool {
return self._secure
}
var sid:String?
public var sid:String? {
return self._sid
}
init(socketURL:String, opts:[String: AnyObject]? = nil) {
var mutURL = RegexMutable(socketURL)
if mutURL["https://"].matches().count != 0 {
public init(var socketURL:String, opts:NSDictionary? = nil) {
if socketURL["https://"].matches().count != 0 {
self._secure = true
}
mutURL = mutURL["http://"] ~= ""
mutURL = mutURL["https://"] ~= ""
socketURL = socketURL["http://"] ~= ""
socketURL = socketURL["https://"] ~= ""
self.socketURL = mutURL
self.reconnectAttempts = -1
self.socketURL = socketURL
// Set options
if opts != nil {
@@ -78,6 +92,8 @@ class SocketIOClient {
if let reconnectAttempts = opts!["reconnectAttempts"] as? Int {
self.reconnectAttempts = reconnectAttempts
} else {
self.reconnectAttempts = -1
}
if let reconnectWait = opts!["reconnectWait"] as? Int {
@@ -91,68 +107,80 @@ class SocketIOClient {
if let polling = opts!["forcePolling"] as? Bool {
self.forcePolling = polling
}
} else {
self.reconnectAttempts = -1
}
super.init()
self.engine = SocketEngine(client: self, forcePolling: self.forcePolling)
}
public convenience init(socketURL:String, options:NSDictionary?) {
self.init(socketURL: socketURL, opts: options)
}
// Closes the socket
func close() {
self.closed = true
self.connecting = false
self.connected = false
self.reconnecting = false
public func close() {
self._closed = true
self._connecting = false
self._connected = false
self._reconnecting = false
self.engine?.close()
}
// Connects to the server
func connect() {
public func connect() {
if self.closed {
println("Warning! This socket was previously closed. This might be dangerous!")
self.closed = false
self._closed = false
}
self.engine.open()
self.engine?.open()
}
// Connect to the server using params
func connectWithParams(params:[String: AnyObject]) {
public func connectWithParams(params:[String: AnyObject]) {
if self.closed {
println("Warning! This socket was previously closed. This might be dangerous!")
self.closed = false
self._closed = false
}
self.params = params
self.paramConnect = true
self.engine.open(opts: params)
self.engine?.open(opts: params)
}
func didConnect() {
self.closed = false
self.connected = true
self.connecting = false
self.reconnecting = false
self._closed = false
self._connected = true
self._connecting = false
self._reconnecting = false
self.currentReconnectAttempt = 0
self.reconnectTimer?.invalidate()
self.reconnectTimer = nil
self._sid = self.engine?.sid
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
self.handleEvent("connect", data: nil, isInternalMessage: false)
}
// Server wants us to die
func didForceClose() {
self.closed = true
self.connected = false
self._closed = true
self._connected = false
self.reconnects = false
self.connecting = false
self.reconnecting = false
self._connecting = false
self._reconnecting = false
self.handleEvent("disconnect", data: "closed", isInternalMessage: true)
}
// Sends a message with multiple args
// If a message contains binary we have to send those
// seperately.
func emit(event:String, _ args:AnyObject...) {
public func emit(event:String, _ args:AnyObject...) {
if !self.connected {
return
}
@@ -163,50 +191,60 @@ class SocketIOClient {
}
}
func emitWithAck(event:String, _ args:AnyObject...) -> SocketAckHandler {
// Objc doesn't have variadics
public func emitObjc(event:String, _ args:[AnyObject]) {
self.emit(event, args)
}
public func emitWithAck(event:String, _ args:AnyObject...) -> SocketAckHandler {
if !self.connected {
return SocketAckHandler(event: "fail")
return SocketAckHandler(event: "fail", socket: self)
}
self.currentAck++
let ackHandler = SocketAckHandler(event: event, ackNum: self.currentAck)
let ackHandler = SocketAckHandler(event: event,
ackNum: self.currentAck, socket: self)
self.ackHandlers.append(ackHandler)
dispatch_async(self.emitQueue) {[weak self] in
self?._emit(event, args, ack: true)
dispatch_async(self.emitQueue) {[weak self, ack = self.currentAck] in
self?._emit(event, args, ack: ack)
return
}
return ackHandler
}
private func _emit(event:String, _ args:[AnyObject], ack:Bool = false) {
public func emitWithAckObjc(event:String, _ args:[AnyObject]) -> SocketAckHandler {
return self.emitWithAck(event, args)
}
private func _emit(event:String, _ args:[AnyObject], ack:Int? = nil) {
var frame:SocketEvent
var str:String
let (items, hasBinary, emitDatas) = SocketIOClient.parseEmitArgs(args)
let (items, hasBinary, emitDatas) = SocketParser.parseEmitArgs(args)
if !self.connected {
return
}
if hasBinary {
if !ack {
if ack == nil {
str = SocketEvent.createMessageForEvent(event, withArgs: items,
hasBinary: true, withDatas: emitDatas.count, toNamespace: self.nsp)
} else {
str = SocketEvent.createMessageForEvent(event, withArgs: items,
hasBinary: true, withDatas: emitDatas.count, toNamespace: self.nsp, wantsAck: self.currentAck)
hasBinary: true, withDatas: emitDatas.count, toNamespace: self.nsp, wantsAck: ack)
}
self.engine?.send(str, datas: emitDatas)
} else {
if !ack {
if ack == nil {
str = SocketEvent.createMessageForEvent(event, withArgs: items, hasBinary: false,
withDatas: 0, toNamespace: self.nsp)
} else {
str = SocketEvent.createMessageForEvent(event, withArgs: items, hasBinary: false,
withDatas: 0, toNamespace: self.nsp, wantsAck: self.currentAck)
withDatas: 0, toNamespace: self.nsp, wantsAck: ack)
}
self.engine?.send(str)
@@ -220,7 +258,7 @@ class SocketIOClient {
return
}
let (items, hasBinary, emitDatas) = SocketIOClient.parseEmitArgs(data!)
let (items, hasBinary, emitDatas) = SocketParser.parseEmitArgs(data!)
var str:String
if !hasBinary {
@@ -248,17 +286,17 @@ class SocketIOClient {
}
// Called when the socket gets an ack for something it sent
private func handleAck(ack:Int, data:AnyObject?) {
func handleAck(ack:Int, data:AnyObject?) {
self.ackHandlers = self.ackHandlers.filter {handler in
if handler.ackNum != ack {
return true
} else {
if data is NSArray {
handler.callback?(data as? NSArray)
handler.executeAck(data as? NSArray)
} else if data != nil {
handler.callback?([data!])
handler.executeAck([data!])
} else {
handler.callback?(nil)
handler.executeAck(nil)
}
return false
@@ -267,7 +305,7 @@ class SocketIOClient {
}
// Handles events
func handleEvent(event:String, data:AnyObject?, isInternalMessage:Bool = false,
public func handleEvent(event:String, data:AnyObject?, isInternalMessage:Bool = false,
wantsAck ack:Int? = nil, withAckType ackType:Int = 3) {
// println("Should do event: \(event) with data: \(data)")
if !self.connected && !isInternalMessage {
@@ -316,487 +354,56 @@ class SocketIOClient {
}
// Adds handler for an event
func on(name:String, callback:NormalCallback) {
public func on(name:String, callback:NormalCallback) {
let handler = SocketEventHandler(event: name, callback: callback)
self.handlers.append(handler)
}
// Adds a handler for any event
func onAny(handler:(AnyHandler) -> Void) {
public func onAny(handler:(AnyHandler) -> Void) {
self.anyHandler = handler
}
// Opens the connection to the socket
func open() {
public func open() {
self.connect()
}
// Parse an NSArray looking for binary data
private class func parseArray(arr:NSArray, var currentPlaceholder:Int) -> (NSArray, Bool, [NSData]) {
var replacementArr = [AnyObject](count: arr.count, repeatedValue: 1)
var hasBinary = false
var arrayDatas = [NSData]()
for g in 0..<arr.count {
if arr[g] is NSData {
hasBinary = true
currentPlaceholder++
let sendData = arr[g] as NSData
arrayDatas.append(sendData)
replacementArr[g] = ["_placeholder": true,
"num": currentPlaceholder]
} else if let dict = arr[g] as? NSDictionary {
let (nestDict, hadBinary, dictArrs) = self.parseNSDictionary(dict,
currentPlaceholder: currentPlaceholder)
if hadBinary {
hasBinary = true
currentPlaceholder += dictArrs.count
replacementArr[g] = nestDict
arrayDatas.extend(dictArrs)
} else {
replacementArr[g] = dict
}
} else if let nestArr = arr[g] as? NSArray {
// Recursive
let (nested, hadBinary, nestDatas) = self.parseArray(nestArr,
currentPlaceholder: currentPlaceholder)
if hadBinary {
hasBinary = true
currentPlaceholder += nestDatas.count
replacementArr[g] = nested
arrayDatas.extend(nestDatas)
} else {
replacementArr[g] = arr[g]
}
} else {
replacementArr[g] = arr[g]
}
}
return (replacementArr, hasBinary, arrayDatas)
func parseSocketMessage(msg:String) {
SocketParser.parseSocketMessage(msg, socket: self)
}
// Parses data for events
class func parseData(data:String?) -> AnyObject? {
if data == nil {
return nil
}
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
}
private class func parseEmitArgs(args:[AnyObject]) -> ([AnyObject], Bool, [NSData]) {
var items = [AnyObject](count: args.count, repeatedValue: 1)
var currentPlaceholder = -1
var hasBinary = false
var emitDatas = [NSData]()
for i in 0..<args.count {
if let dict = args[i] as? NSDictionary {
// Check for binary data
let (newDict, hadBinary, binaryDatas) = SocketIOClient.parseNSDictionary(dict,
currentPlaceholder: currentPlaceholder)
if hadBinary {
currentPlaceholder += binaryDatas.count
emitDatas.extend(binaryDatas)
hasBinary = true
items[i] = newDict
} else {
items[i] = dict
}
} else if let arr = args[i] as? NSArray {
// arg is array, check for binary
let (replace, hadData, newDatas) = SocketIOClient.parseArray(arr,
currentPlaceholder: currentPlaceholder)
if hadData {
hasBinary = true
currentPlaceholder += newDatas.count
for data in newDatas {
emitDatas.append(data)
}
items[i] = replace
} else {
items[i] = arr
}
} else if let binaryData = args[i] as? NSData {
// args is just binary
hasBinary = true
currentPlaceholder++
items[i] = ["_placeholder": true, "num": currentPlaceholder]
emitDatas.append(binaryData)
} else {
items[i] = args[i]
}
}
return (items, hasBinary, emitDatas)
}
// Parses a NSDictionary, looking for NSData objects
private class func parseNSDictionary(dict:NSDictionary, var currentPlaceholder:Int) -> (NSDictionary, Bool, [NSData]) {
var returnDict = NSMutableDictionary()
var hasBinary = false
var returnDatas = [NSData]()
for (key, value) in dict {
if let binaryData = value as? NSData {
currentPlaceholder++
hasBinary = true
returnDatas.append(binaryData)
returnDict[key as String] = ["_placeholder": true, "num": currentPlaceholder++]
} else if let arr = value as? NSArray {
let (replace, hadBinary, arrDatas) = self.parseArray(arr, currentPlaceholder: currentPlaceholder)
if hadBinary {
hasBinary = true
returnDict[key as String] = replace
currentPlaceholder += arrDatas.count
returnDatas.extend(arrDatas)
} else {
returnDict[key as String] = arr
}
} else if let dict = value as? NSDictionary {
// Recursive
let (nestDict, hadBinary, nestDatas) = self.parseNSDictionary(dict, currentPlaceholder: currentPlaceholder)
if hadBinary {
hasBinary = true
returnDict[key as String] = nestDict
currentPlaceholder += nestDatas.count
returnDatas.extend(nestDatas)
} else {
returnDict[key as String] = dict
}
} else {
returnDict[key as String] = value
}
}
return (returnDict, hasBinary, returnDatas)
}
// Parses messages recieved
func parseSocketMessage(message:AnyObject?) {
if message == nil {
return
}
// println(message!)
if let stringMessage = message as? String {
// Check for successful namepsace connect
if self.nsp != nil {
if stringMessage == "0/\(self.nsp!)" {
self.didConnect()
return
}
}
if stringMessage == "0" {
if self.nsp != nil {
// Join namespace
self.joinNamespace()
return
} else {
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
self.didConnect()
return
}
}
var mutMessage = RegexMutable(stringMessage)
/**
Begin check for message
**/
let messageGroups = mutMessage["(\\d*)\\/?(\\w*)?,?(\\d*)?(\\[.*\\])?"].groups()
if messageGroups[1].hasPrefix("2") {
var mesNum = messageGroups[1]
var ackNum:String
var namespace:String?
var messagePart:String!
if messageGroups[3] != "" {
ackNum = messageGroups[3]
} else {
let range = Range<String.Index>(start: mesNum.startIndex, end: advance(mesNum.startIndex, 1))
mesNum.replaceRange(range, with: "")
ackNum = mesNum
}
namespace = messageGroups[2]
messagePart = messageGroups[4]
if namespace == "" && self.nsp != nil {
return
}
let messageInternals = RegexMutable(messagePart)["\\[\"(.*?)\",(.*?)?\\]$"].groups()
if messageInternals != nil && messageInternals.count > 2 {
let event = messageInternals[1]
var data:String?
if messageInternals[2] == "" {
data = nil
} else {
data = messageInternals[2]
}
// It would be nice if socket.io only allowed one thing
// per message, but alas, it doesn't.
if let parsed:AnyObject = SocketIOClient.parseData(data) {
if ackNum == "" {
self.handleEvent(event, data: parsed)
} else {
self.currentAck = ackNum.toInt()!
self.handleEvent(event, data: parsed, isInternalMessage: false,
wantsAck: ackNum.toInt(), withAckType: 3)
}
return
} else if let strData = data {
// There are multiple items in the message
// Turn it into a String and run it through
// parseData to try and get an array.
let asArray = "[\(strData)]"
if let parsed:AnyObject = SocketIOClient.parseData(asArray) {
if ackNum == "" {
self.handleEvent(event, data: parsed)
} else {
self.currentAck = ackNum.toInt()!
self.handleEvent(event, data: parsed, isInternalMessage: false,
wantsAck: ackNum.toInt(), withAckType: 3)
}
return
}
}
}
// Check for no item event
let noItemMessage = RegexMutable(messagePart)["\\[\"(.*?)\"]$"].groups()
if noItemMessage != nil && noItemMessage.count == 2 {
let event = noItemMessage[1]
if ackNum == "" {
self.handleEvent(event, data: nil)
} else {
self.currentAck = ackNum.toInt()!
self.handleEvent(event, data: nil, isInternalMessage: false,
wantsAck: ackNum.toInt(), withAckType: 3)
}
return
}
} else if messageGroups[1].hasPrefix("3") {
let arr = Array(messageGroups[1])
var ackNum:String
let nsp = messageGroups[2]
if nsp == "" && self.nsp != nil {
return
}
if nsp == "" {
ackNum = String(arr[1...arr.count-1])
} else {
ackNum = messageGroups[3]
}
let ackData:AnyObject? = SocketIOClient.parseData(messageGroups[4])
self.handleAck(ackNum.toInt()!, data: ackData)
return
}
/**
End Check for message
**/
// Check for message with binary placeholders
self.parseBinaryMessage(message: message!)
}
// Message is binary
if let binary = message as? NSData {
if self.waitingData.isEmpty {
return
}
self.parseBinaryData(binary)
}
}
// Tries to parse a message that contains binary
private func parseBinaryMessage(#message:AnyObject) {
// println(message)
if let stringMessage = message as? String {
var mutMessage = RegexMutable(stringMessage)
/**
Begin check for binary placeholders
**/
let binaryGroup = mutMessage["^(\\d*)-\\/?(\\w*)?,?(\\d*)?\\[(\".*?\")?,?(.*)?\\]$"].groups()
if binaryGroup == nil {
return
}
if binaryGroup[1].hasPrefix("5") {
// println(binaryGroup)
var ackNum:String
var event:String
var mutMessageObject:NSMutableString
var namespace:String?
var numberOfPlaceholders:String
let messageType = RegexMutable(binaryGroup[1])
namespace = binaryGroup[2]
if binaryGroup[3] != "" {
ackNum = binaryGroup[3] as String
} else if self.nsp == nil && binaryGroup[2] != "" {
ackNum = binaryGroup[2]
} else {
ackNum = ""
}
numberOfPlaceholders = (messageType["5"] ~= "") as String
event = (RegexMutable(binaryGroup[4])["\""] ~= "") as String
mutMessageObject = RegexMutable(binaryGroup[5])
if namespace == "" && self.nsp != nil {
return
}
let placeholdersRemoved = mutMessageObject["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"]
~= "\"~~$2\""
var mes:SocketEvent
if ackNum == "" {
mes = SocketEvent(event: event, args: placeholdersRemoved,
placeholders: numberOfPlaceholders.toInt()!)
} else {
self.currentAck = ackNum.toInt()!
mes = SocketEvent(event: event, args: placeholdersRemoved,
placeholders: numberOfPlaceholders.toInt()!, ackNum: ackNum.toInt())
}
self.waitingData.append(mes)
} else if binaryGroup[1].hasPrefix("6") {
let messageType = RegexMutable(binaryGroup[1])
let numberOfPlaceholders = (messageType["6"] ~= "") as String
var ackNum:String
var nsp:String
if binaryGroup[3] == "" {
ackNum = binaryGroup[2]
nsp = ""
} else {
ackNum = binaryGroup[3]
nsp = binaryGroup[2]
}
if nsp == "" && self.nsp != nil {
return
}
var mutMessageObject = RegexMutable(binaryGroup[5])
let placeholdersRemoved = mutMessageObject["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"]
~= "\"~~$2\""
let event = SocketEvent(event: "", args: placeholdersRemoved,
placeholders: numberOfPlaceholders.toInt()!, ackNum: ackNum.toInt(), justAck: true)
self.waitingData.append(event)
}
/**
End check for binary placeholders
**/
}
}
// Handles binary data
private func parseBinaryData(data:NSData) {
let shouldExecute = self.waitingData[0].addData(data)
if shouldExecute {
let socketEvent = self.waitingData.removeAtIndex(0)
var event = socketEvent.event
var parsedArgs:AnyObject? = SocketIOClient.parseData(socketEvent.args as? String)
if let args:AnyObject = parsedArgs {
let filledInArgs:AnyObject = socketEvent.fillInPlaceholders(args)
if socketEvent.justAck! {
// Should handle ack
self.handleAck(socketEvent.ack!, data: filledInArgs)
return
}
// Should do event
if socketEvent.ack != nil {
self.handleEvent(event, data: filledInArgs, isInternalMessage: false,
wantsAck: socketEvent.ack!, withAckType: 6)
} else {
self.handleEvent(event, data: filledInArgs)
}
} else {
let filledInArgs:AnyObject = socketEvent.fillInPlaceholders()
// Should handle ack
if socketEvent.justAck! {
self.handleAck(socketEvent.ack!, data: filledInArgs)
return
}
// Should handle ack
if socketEvent.ack != nil {
self.handleEvent(event, data: filledInArgs, isInternalMessage: false,
wantsAck: socketEvent.ack!, withAckType: 6)
} else {
self.handleEvent(event, data: filledInArgs)
}
}
}
func parseBinaryData(data:NSData) {
SocketParser.parseBinaryData(data, socket: self)
}
// Something happened while polling
func pollingDidFail(err:NSError?) {
if !self.reconnecting {
self.connected = false
self._connected = false
self.handleEvent("reconnect", data: err?.localizedDescription, isInternalMessage: true)
self.tryReconnect()
}
}
func removeAck(ack:SocketAckHandler) {
self.ackHandlers = self.ackHandlers.filter {$0 === ack ? false : true}
}
// We lost connection and should attempt to reestablish
@objc func tryReconnect() {
func tryReconnect() {
if self.reconnectAttempts != -1 && self.currentReconnectAttempt + 1 > self.reconnectAttempts {
self.didForceClose()
return
} else if self.connected {
self.connecting = false
self.reconnecting = false
self._connecting = false
self._reconnecting = false
return
}
if self.reconnectTimer == nil {
self.reconnecting = true
self._reconnecting = true
dispatch_async(dispatch_get_main_queue()) {[weak self] in
if self == nil {
return
@@ -806,8 +413,6 @@ class SocketIOClient {
target: self!, selector: "tryReconnect", userInfo: nil, repeats: true)
return
}
return
}
self.handleEvent("reconnectAttempt", data: self.reconnectAttempts - self.currentReconnectAttempt,
@@ -823,8 +428,8 @@ class SocketIOClient {
// Called when the socket is closed
func webSocketDidCloseWithCode(code:Int, reason:String!, wasClean:Bool) {
self.connected = false
self.connecting = false
self._connected = false
self._connecting = false
if self.closed || !self.reconnects {
self.didForceClose()
} else {
@@ -835,8 +440,8 @@ class SocketIOClient {
// Called when an error occurs.
func webSocketDidFailWithError(error:NSError!) {
self.connected = false
self.connecting = false
self._connected = false
self._connecting = false
self.handleEvent("error", data: error.localizedDescription, isInternalMessage: true)
if self.closed || !self.reconnects {
self.didForceClose()
+438
View File
@@ -0,0 +1,438 @@
//
// 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 {
// Parse an NSArray looking for binary data
class func parseArray(arr:NSArray, var currentPlaceholder:Int) -> (NSArray, Bool, [NSData]) {
var replacementArr = [AnyObject](count: arr.count, repeatedValue: 1)
var hasBinary = false
var arrayDatas = [NSData]()
for g in 0..<arr.count {
if arr[g] is NSData {
hasBinary = true
currentPlaceholder++
let sendData = arr[g] as NSData
arrayDatas.append(sendData)
replacementArr[g] = ["_placeholder": true,
"num": currentPlaceholder]
} else if let dict = arr[g] as? NSDictionary {
let (nestDict, hadBinary, dictArrs) = self.parseNSDictionary(dict,
currentPlaceholder: currentPlaceholder)
if hadBinary {
hasBinary = true
currentPlaceholder += dictArrs.count
replacementArr[g] = nestDict
arrayDatas.extend(dictArrs)
} else {
replacementArr[g] = dict
}
} else if let nestArr = arr[g] as? NSArray {
// Recursive
let (nested, hadBinary, nestDatas) = self.parseArray(nestArr,
currentPlaceholder: currentPlaceholder)
if hadBinary {
hasBinary = true
currentPlaceholder += nestDatas.count
replacementArr[g] = nested
arrayDatas.extend(nestDatas)
} else {
replacementArr[g] = arr[g]
}
} else {
replacementArr[g] = arr[g]
}
}
return (replacementArr, hasBinary, arrayDatas)
}
// Parses data for events
class func parseData(data:String?) -> AnyObject? {
if data == nil {
return nil
}
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 parseEmitArgs(args:[AnyObject]) -> ([AnyObject], Bool, [NSData]) {
var items = [AnyObject](count: args.count, repeatedValue: 1)
var currentPlaceholder = -1
var hasBinary = false
var emitDatas = [NSData]()
for i in 0..<args.count {
if let dict = args[i] as? NSDictionary {
// Check for binary data
let (newDict, hadBinary, binaryDatas) = self.parseNSDictionary(dict,
currentPlaceholder: currentPlaceholder)
if hadBinary {
currentPlaceholder += binaryDatas.count
emitDatas.extend(binaryDatas)
hasBinary = true
items[i] = newDict
} else {
items[i] = dict
}
} else if let arr = args[i] as? NSArray {
// arg is array, check for binary
let (replace, hadData, newDatas) = self.parseArray(arr,
currentPlaceholder: currentPlaceholder)
if hadData {
hasBinary = true
currentPlaceholder += newDatas.count
for data in newDatas {
emitDatas.append(data)
}
items[i] = replace
} else {
items[i] = arr
}
} else if let binaryData = args[i] as? NSData {
// args is just binary
hasBinary = true
currentPlaceholder++
items[i] = ["_placeholder": true, "num": currentPlaceholder]
emitDatas.append(binaryData)
} else {
items[i] = args[i]
}
}
return (items, hasBinary, emitDatas)
}
// Parses a NSDictionary, looking for NSData objects
class func parseNSDictionary(dict:NSDictionary, var currentPlaceholder:Int) -> (NSDictionary, Bool, [NSData]) {
var returnDict = NSMutableDictionary()
var hasBinary = false
var returnDatas = [NSData]()
for (key, value) in dict {
if let binaryData = value as? NSData {
currentPlaceholder++
hasBinary = true
returnDatas.append(binaryData)
returnDict[key as String] = ["_placeholder": true, "num": currentPlaceholder]
} else if let arr = value as? NSArray {
let (replace, hadBinary, arrDatas) = self.parseArray(arr, currentPlaceholder: currentPlaceholder)
if hadBinary {
hasBinary = true
returnDict[key as String] = replace
currentPlaceholder += arrDatas.count
returnDatas.extend(arrDatas)
} else {
returnDict[key as String] = arr
}
} else if let dict = value as? NSDictionary {
// Recursive
let (nestDict, hadBinary, nestDatas) = self.parseNSDictionary(dict, currentPlaceholder: currentPlaceholder)
if hadBinary {
hasBinary = true
returnDict[key as String] = nestDict
currentPlaceholder += nestDatas.count
returnDatas.extend(nestDatas)
} else {
returnDict[key as String] = dict
}
} else {
returnDict[key as String] = value
}
}
return (returnDict, hasBinary, returnDatas)
}
// Parses messages recieved
class func parseSocketMessage(stringMessage:String, socket:SocketIOClient) {
if stringMessage == "" {
return
}
// NSLog(stringMessage)
// Check for successful namepsace connect
if socket.nsp != nil {
if stringMessage == "0/\(socket.nsp!)" {
socket.didConnect()
return
}
}
if stringMessage == "0" {
if socket.nsp != nil {
// Join namespace
socket.joinNamespace()
return
} else {
socket.didConnect()
return
}
}
if stringMessage.hasPrefix("5") || stringMessage.hasPrefix("6") {
// Check for message with binary placeholders
self.parseBinaryMessage(stringMessage, socket: socket)
return
}
/**
Begin check for message
**/
var messageGroups:[String]?
if let groups = stringMessage["(\\d*)\\/?(\\w*)?,?(\\d*)?\\[\"(.*?)\",?(.*?)?\\]$",
NSRegularExpressionOptions.DotMatchesLineSeparators].groups() {
messageGroups = groups
} else if let ackGroup = stringMessage["(\\d*)\\/?(\\w*)?,?(\\d*)?\\[(.*?)?\\]$",
NSRegularExpressionOptions.DotMatchesLineSeparators].groups() {
messageGroups = ackGroup
} else {
NSLog("Error parsing message: %s", stringMessage)
return
}
if messageGroups![1].hasPrefix("2") {
var mesNum = messageGroups![1]
var ackNum:String
var namespace:String?
if messageGroups![3] != "" {
ackNum = messageGroups![3]
} else {
let range = Range<String.Index>(start: mesNum.startIndex,
end: advance(mesNum.startIndex, 1))
mesNum.replaceRange(range, with: "")
ackNum = mesNum
}
namespace = messageGroups![2]
if namespace == "" && socket.nsp != nil {
return
}
let event = messageGroups![4]
let data = "[\(messageGroups![5])]"
if let parsed:AnyObject = self.parseData(data) {
if ackNum == "" {
socket.handleEvent(event, data: parsed)
} else {
socket.currentAck = ackNum.toInt()!
socket.handleEvent(event, data: parsed, isInternalMessage: false,
wantsAck: ackNum.toInt(), withAckType: 3)
}
return
}
} else if messageGroups![1].hasPrefix("3") {
let arr = Array(messageGroups![1])
var ackNum:String
let nsp = messageGroups![2]
if nsp == "" && socket.nsp != nil {
return
}
if nsp == "" {
ackNum = String(arr[1...arr.count-1])
} else {
ackNum = messageGroups![3]
}
let ackData:AnyObject? = self.parseData(messageGroups![4])
socket.handleAck(ackNum.toInt()!, data: ackData)
return
}
/**
End Check for message
**/
}
// 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 {
let socketEvent = socket.waitingData.removeAtIndex(0)
var event = socketEvent.event
var parsedArgs:AnyObject? = self.parseData(socketEvent.args as? String)
if let args:AnyObject = parsedArgs {
let filledInArgs:AnyObject = socketEvent.fillInPlaceholders(args)
if socketEvent.justAck! {
// Should handle ack
socket.handleAck(socketEvent.ack!, data: filledInArgs)
return
}
// Should do event
if socketEvent.ack != nil {
socket.handleEvent(event, data: filledInArgs, isInternalMessage: false,
wantsAck: socketEvent.ack!, withAckType: 6)
} else {
socket.handleEvent(event, data: filledInArgs)
}
} else {
let filledInArgs:AnyObject = socketEvent.fillInPlaceholders()
// Should handle ack
if socketEvent.justAck! {
socket.handleAck(socketEvent.ack!, data: filledInArgs)
return
}
// Should handle ack
if socketEvent.ack != nil {
socket.handleEvent(event, data: filledInArgs, isInternalMessage: false,
wantsAck: socketEvent.ack!, withAckType: 6)
} else {
socket.handleEvent(event, data: filledInArgs)
}
}
}
}
// Tries to parse a message that contains binary
class func parseBinaryMessage(message:String, socket:SocketIOClient) {
// NSLog(message)
/**
Begin check for binary placeholders
**/
var binaryGroup:[String]?
if let groups = message["^(\\d*)-\\/?(\\w*)?,?(\\d*)?\\[(\".*?\")?,?(.*)?\\]$",
NSRegularExpressionOptions.DotMatchesLineSeparators].groups() {
binaryGroup = groups
} else if let groups = message["^(\\d*)-\\/?(\\w*)?,?(\\d*)?\\[(.*?)?\\]$",
NSRegularExpressionOptions.DotMatchesLineSeparators].groups() {
binaryGroup = groups
} else {
NSLog("Error in parsing binary message: %s", message)
return
}
if binaryGroup![1].hasPrefix("5") {
// println(binaryGroup)
var ackNum:String
var event:String
var mutMessageObject:String
var namespace:String?
var numberOfPlaceholders:String
let messageType = binaryGroup![1]
namespace = binaryGroup![2]
if binaryGroup![3] != "" {
ackNum = binaryGroup![3] as String
} else if socket.nsp == nil && binaryGroup![2] != "" {
ackNum = binaryGroup![2]
} else {
ackNum = ""
}
numberOfPlaceholders = (messageType["5"] ~= "") as String
event = (binaryGroup![4]["\""] ~= "") as String
mutMessageObject = binaryGroup![5]
if namespace == "" && socket.nsp != nil {
return
}
let placeholdersRemoved = mutMessageObject["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"]
~= "\"~~$2\""
var mes:SocketEvent
if ackNum == "" {
mes = SocketEvent(event: event, args: placeholdersRemoved,
placeholders: numberOfPlaceholders.toInt()!)
} else {
socket.currentAck = ackNum.toInt()!
mes = SocketEvent(event: event, args: placeholdersRemoved,
placeholders: numberOfPlaceholders.toInt()!, ackNum: ackNum.toInt())
}
socket.waitingData.append(mes)
} else if binaryGroup![1].hasPrefix("6") {
let messageType = binaryGroup![1]
let numberOfPlaceholders = (messageType["6"] ~= "") as String
var ackNum:String
var nsp:String
if binaryGroup![3] == "" {
ackNum = binaryGroup![2]
nsp = ""
} else {
ackNum = binaryGroup![3]
nsp = binaryGroup![2]
}
if nsp == "" && socket.nsp != nil {
return
}
var mutMessageObject = binaryGroup![5]
let placeholdersRemoved = mutMessageObject["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"]
~= "\"~~$2\""
let event = SocketEvent(event: "", args: placeholdersRemoved,
placeholders: numberOfPlaceholders.toInt()!, ackNum: ackNum.toInt(), justAck: true)
socket.waitingData.append(event)
}
/**
End check for binary placeholders
**/
}
}
+47 -167
View File
@@ -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
@@ -44,12 +43,12 @@ public class SwiftRegex: NSObject, BooleanType {
}
final var targetRange: NSRange {
return NSRange(location: 0,length: target.length)
return NSRange(location: 0,length: countElements(target))
}
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
}
@@ -63,19 +62,19 @@ public class SwiftRegex: NSObject, BooleanType {
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
@@ -87,19 +86,23 @@ public class SwiftRegex: NSObject, BooleanType {
}
}
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
}
}
}
@@ -120,24 +123,23 @@ public class SwiftRegex: NSObject, BooleanType {
}
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 {
options:NSMatchingOptions = nil) -> String {
let out = NSMutableString()
var pos = 0
@@ -145,63 +147,21 @@ public class SwiftRegex: NSObject, BooleanType {
(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 )
out.appendString(substring( NSRange(location:pos, length:targetRange.length-pos))!)
if let mutableTarget = target as? NSMutableString {
mutableTarget.setString(out as String)
return mutableTarget
} else {
SwiftRegex.failure("Modify on non-mutable")
return out
}
}
/* removed Beta6
public func __conversion() -> Bool {
return doesMatch()
return out
}
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,18 +174,14 @@ 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)
}, options: nil)
}
public func ~= (left: SwiftRegex, right: [String]) -> NSMutableString {
public func ~= (left: SwiftRegex, right: [String]) -> String {
var matchNumber = 0
return left.substituteMatches({match, stop -> String in
@@ -235,95 +191,19 @@ public func ~= (left: SwiftRegex, right: [String]) -> NSMutableString {
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) -> 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)
}
+714
View File
@@ -0,0 +1,714 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import CoreFoundation
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: NSError?)
func websocketDidReceiveMessage(socket: WebSocket, text: String)
func websocketDidReceiveData(socket: WebSocket, data: NSData)
}
public class WebSocket : NSObject, NSStreamDelegate {
enum OpCode : UInt8 {
case ContinueFrame = 0x0
case TextFrame = 0x1
case BinaryFrame = 0x2
//3-7 are reserved.
case ConnectionClose = 0x8
case Ping = 0x9
case Pong = 0xA
//B-F reserved.
}
enum CloseCode : UInt16 {
case Normal = 1000
case GoingAway = 1001
case ProtocolError = 1002
case ProtocolUnhandledType = 1003
// 1004 reserved.
case NoStatusReceived = 1005
//1006 reserved.
case Encoding = 1007
case PolicyViolated = 1008
case MessageTooBig = 1009
}
enum InternalErrorCode : UInt16 {
// 0-999 WebSocket status codes not used
case OutputStreamWriteError = 1
}
//Where the callback is executed. It defaults to the main UI thread queue.
public var queue = dispatch_get_main_queue()
var optionalProtocols : Array<String>?
//Constant Values.
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 2048
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
class WSResponse {
var isFin = false
var code: OpCode = .ContinueFrame
var bytesLeft = 0
var frameCount = 0
var buffer: NSMutableData?
}
public weak var delegate: WebSocketDelegate?
private var url: NSURL
private var inputStream: NSInputStream?
private var outputStream: NSOutputStream?
private var isRunLoop = false
private var connected = false
private var writeQueue: NSOperationQueue?
private var readStack = Array<WSResponse>()
private var inputQueue = Array<NSData>()
private var fragBuffer: NSData?
public var headers = Dictionary<String,String>()
public var voipEnabled = false
public var selfSignedSSL = false
private var connectedBlock: ((Void) -> Void)? = nil
private var disconnectedBlock: ((NSError?) -> Void)? = nil
private var receivedTextBlock: ((String) -> Void)? = nil
private var receivedDataBlock: ((NSData) -> Void)? = nil
public var isConnected :Bool {
return connected
}
//init the websocket with a url
public init(url: NSURL) {
self.url = url
}
//used for setting protocols.
public convenience init(url: NSURL, protocols: Array<String>) {
self.init(url: url)
optionalProtocols = protocols
}
//closure based instead of the delegate
public convenience init(url: NSURL, protocols: Array<String>, connect:((Void) -> Void), disconnect:((NSError?) -> Void), text:((String) -> Void), data:(NSData) -> Void) {
self.init(url: url, protocols: protocols)
connectedBlock = connect
disconnectedBlock = disconnect
receivedTextBlock = text
receivedDataBlock = data
}
//same as above, just shorter
public convenience init(url: NSURL, connect:((Void) -> Void), disconnect:((NSError?) -> Void), text:((String) -> Void)) {
self.init(url: url)
connectedBlock = connect
disconnectedBlock = disconnect
receivedTextBlock = text
}
//same as above, just shorter
public convenience init(url: NSURL, connect:((Void) -> Void), disconnect:((NSError?) -> Void), data:((NSData) -> Void)) {
self.init(url: url)
connectedBlock = connect
disconnectedBlock = disconnect
receivedDataBlock = data
}
///Connect to the websocket server on a background thread
public func connect() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), {
self.createHTTPRequest()
})
}
///disconnect from the websocket server
public func disconnect() {
writeError(CloseCode.Normal.rawValue)
}
///write a string to the websocket. This sends it as a text frame.
public func writeString(str: String) {
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame)
}
///write binary data to the websocket. This sends it as a binary frame.
public func writeData(data: NSData) {
dequeueWrite(data, code: .BinaryFrame)
}
//write a ping to the websocket. This sends it as a control frame.
//yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
public func writePing(data: NSData) {
dequeueWrite(data, code: .Ping)
}
//private methods below!
//private method that starts the connection
private func createHTTPRequest() {
let str: NSString = url.absoluteString!
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
url, kCFHTTPVersion1_1)
var port = url.port
if port == nil {
if url.scheme == "wss" || url.scheme == "https" {
port = 443
} else {
port = 80
}
}
self.addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
self.addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
if let protocols = optionalProtocols {
self.addHeader(urlRequest, key: headerWSProtocolName, val: ",".join(protocols))
}
self.addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
self.addHeader(urlRequest, key: headerWSKeyName, val: self.generateWebSocketKey())
self.addHeader(urlRequest, key: headerOriginName, val: url.absoluteString!)
self.addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
for (key,value) in headers {
self.addHeader(urlRequest, key: key, val: value)
}
let serializedRequest: NSData = CFHTTPMessageCopySerializedMessage(urlRequest.takeUnretainedValue()).takeUnretainedValue()
self.initStreamsWithData(serializedRequest, Int(port!))
}
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
private func addHeader(urlRequest: Unmanaged<CFHTTPMessage>,key: String, val: String) {
let nsKey: NSString = key
let nsVal: NSString = val
CFHTTPMessageSetHeaderFieldValue(urlRequest.takeUnretainedValue(),
nsKey,
nsVal)
}
//generate a websocket key as needed in rfc
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for (var i = 0; i < seed; i++) {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni))"
}
var data = key.dataUsingEncoding(NSUTF8StringEncoding)
var baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0))
return baseKey!
}
//Start the stream connection and write the data to the output stream
private func initStreamsWithData(data: NSData, _ port: Int) {
//higher level API we will cut over to at some point
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h: NSString = url.host!
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeUnretainedValue()
outputStream = writeStream!.takeUnretainedValue()
inputStream!.delegate = self
outputStream!.delegate = self
if url.scheme == "wss" || url.scheme == "https" {
inputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
outputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
}
if self.voipEnabled {
inputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
outputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
}
if self.selfSignedSSL {
let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings)
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings)
}
isRunLoop = true
inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream!.open()
outputStream!.open()
let bytes = UnsafePointer<UInt8>(data.bytes)
outputStream!.write(bytes, maxLength: data.length)
while(isRunLoop) {
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as NSDate)
}
}
//delegate for the stream methods. Processes incoming bytes
func stream(aStream: NSStream!, handleEvent eventCode: NSStreamEvent) {
if eventCode == .HasBytesAvailable {
if(aStream == inputStream) {
processInputStream()
}
} else if eventCode == .ErrorOccurred {
disconnectStream(aStream!.streamError)
} else if eventCode == .EndEncountered {
disconnectStream(nil)
}
}
//disconnect the stream object
private func disconnectStream(error: NSError?) {
if writeQueue != nil {
writeQueue!.waitUntilAllOperationsAreFinished()
}
inputStream!.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream!.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream!.close()
outputStream!.close()
inputStream = nil
outputStream = nil
isRunLoop = false
connected = false
dispatch_async(queue,{
if let disconnectBlock = self.disconnectedBlock {
disconnectBlock(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
})
}
///handles the incoming bytes and sending them to the proper processing method
private func processInputStream() {
let buf = NSMutableData(capacity: BUFFER_MAX)
var buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
if length > 0 {
if !connected {
connected = processHTTP(buffer, bufferLen: length)
if !connected {
dispatch_async(queue,{
//self.workaroundMethod()
let error = self.errorWithDetail("Invalid HTTP upgrade", code: 1)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
})
}
} else {
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(NSData(bytes: buffer, length: length))
if process {
dequeueInput()
}
}
}
}
///dequeue the incoming input so it is processed in order
private func dequeueInput() {
if inputQueue.count > 0 {
let data = inputQueue[0]
var work = data
if (fragBuffer != nil) {
var combine = NSMutableData(data: fragBuffer!)
combine.appendData(data)
work = combine
fragBuffer = nil
}
let buffer = UnsafePointer<UInt8>(work.bytes)
processRawMessage(buffer, bufferLen: work.length)
inputQueue = inputQueue.filter{$0 != data}
dequeueInput()
}
}
///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")]
var k = 0
var totalSize = 0
for var i = 0; i < bufferLen; i++ {
if buffer[i] == CRLFBytes[k] {
k++
if k == 3 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
if validateResponse(buffer, bufferLen: totalSize) {
dispatch_async(queue,{
//self.workaroundMethod()
if let connectBlock = self.connectedBlock {
connectBlock()
}
self.delegate?.websocketDidConnect(self)
})
totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessage((buffer+totalSize),bufferLen: restSize)
}
return true
}
}
return false
}
///validates the HTTP is a 101 as per the RFC spec
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, 0)
CFHTTPMessageAppendBytes(response.takeUnretainedValue(), buffer, bufferLen)
if CFHTTPMessageGetResponseStatusCode(response.takeUnretainedValue()) != 101 {
return false
}
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response.takeUnretainedValue())
let headers: NSDictionary = cfHeaders.takeUnretainedValue()
let acceptKey = headers[headerWSAcceptName] as NSString
if acceptKey.length > 0 {
return true
}
return false
}
///process the websocket data
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
var response = readStack.last
if response != nil && bufferLen < 2 {
fragBuffer = NSData(bytes: buffer, length: bufferLen)
return
}
if response != nil && response!.bytesLeft > 0 {
let resp = response!
var len = resp.bytesLeft
var extra = bufferLen - resp.bytesLeft
if resp.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
resp.bytesLeft -= len
resp.buffer?.appendData(NSData(bytes: buffer, length: len))
processResponse(resp)
var offset = bufferLen - extra
if extra > 0 {
processExtra((buffer+offset), bufferLen: extra)
}
return
} else {
let isFin = (FinMask & buffer[0])
let receivedOpcode = (OpCodeMask & buffer[0])
let isMasked = (MaskMask & buffer[1])
let payloadLen = (PayloadLenMask & buffer[1])
var offset = 2
if((isMasked > 0 || (RSVMask & buffer[0]) > 0) && receivedOpcode != OpCode.Pong.rawValue) {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("masked and rsv data is not currently supported", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
let isControlFrame = (receivedOpcode == OpCode.ConnectionClose.rawValue || receivedOpcode == OpCode.Ping.rawValue)
if !isControlFrame && (receivedOpcode != OpCode.BinaryFrame.rawValue && receivedOpcode != OpCode.ContinueFrame.rawValue &&
receivedOpcode != OpCode.TextFrame.rawValue && receivedOpcode != OpCode.Pong.rawValue) {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("control frames can't be fragmented", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
if receivedOpcode == OpCode.ConnectionClose.rawValue {
var code = CloseCode.Normal.rawValue
if payloadLen == 1 {
code = CloseCode.ProtocolError.rawValue
} else if payloadLen > 1 {
var codeBuffer = UnsafePointer<UInt16>((buffer+offset))
code = codeBuffer[0].byteSwapped
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
code = CloseCode.ProtocolError.rawValue
}
offset += 2
}
if payloadLen > 2 {
let len = Int(payloadLen-2)
if len > 0 {
let bytes = UnsafePointer<UInt8>((buffer+offset))
var str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
if str == nil {
code = CloseCode.ProtocolError.rawValue
}
}
}
let error = self.errorWithDetail("connection closed by server", code: code)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(code)
return
}
if isControlFrame && payloadLen > 125 {
writeError(CloseCode.ProtocolError.rawValue)
return
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
let bytes = UnsafePointer<UInt64>((buffer+offset))
dataLength = bytes[0].byteSwapped
offset += sizeof(UInt64)
} else if dataLength == 126 {
let bytes = UnsafePointer<UInt16>((buffer+offset))
dataLength = UInt64(bytes[0].byteSwapped)
offset += sizeof(UInt16)
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
var data: NSData!
if len < 0 {
len = 0
data = NSData()
} else {
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
}
if receivedOpcode == OpCode.Pong.rawValue {
let step = Int(offset+len)
let extra = bufferLen-step
if extra > 0 {
processRawMessage((buffer+step), bufferLen: extra)
}
return
}
var response = readStack.last
if isControlFrame {
response = nil //don't append pings
}
if isFin == 0 && receivedOpcode == OpCode.ContinueFrame.rawValue && response == nil {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("continue frame before a binary or text frame", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
var isNew = false
if(response == nil) {
if receivedOpcode == OpCode.ContinueFrame.rawValue {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("first frame can't be a continue frame",
code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
isNew = true
response = WSResponse()
response!.code = OpCode(rawValue: receivedOpcode)!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == OpCode.ContinueFrame.rawValue {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("second and beyond of fragment message must be a continue frame",
code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
response!.buffer!.appendData(data)
}
if response != nil {
response!.bytesLeft -= Int(len)
response!.frameCount++
response!.isFin = isFin > 0 ? true : false
if(isNew) {
readStack.append(response!)
}
processResponse(response!)
}
let step = Int(offset+len)
let extra = bufferLen-step
if(extra > 0) {
processExtra((buffer+step), bufferLen: extra)
}
}
}
///process the extra of a buffer
private func processExtra(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
if bufferLen < 2 {
fragBuffer = NSData(bytes: buffer, length: bufferLen)
} else {
processRawMessage(buffer, bufferLen: bufferLen)
}
}
///process the finished response of a buffer
private func processResponse(response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .Ping {
let data = response.buffer! //local copy so it is perverse for writing
dequeueWrite(data, code: OpCode.Pong)
} else if response.code == .TextFrame {
var str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
if str == nil {
writeError(CloseCode.Encoding.rawValue)
return false
}
dispatch_async(queue,{
if let textBlock = self.receivedTextBlock{
textBlock(str!)
}
self.delegate?.websocketDidReceiveMessage(self, text: str!)
})
} else if response.code == .BinaryFrame {
let data = response.buffer! //local copy so it is perverse for writing
dispatch_async(queue,{
//self.workaroundMethod()
if let dataBlock = self.receivedDataBlock{
dataBlock(data)
}
self.delegate?.websocketDidReceiveData(self, data: data)
})
}
readStack.removeLast()
return true
}
return false
}
///Create an error
private func errorWithDetail(detail: String, code: UInt16) -> NSError {
var details = Dictionary<String,String>()
details[NSLocalizedDescriptionKey] = detail
return NSError(domain: "Websocket", code: Int(code), userInfo: details)
}
///write a an error to the socket
private func writeError(code: UInt16) {
let buf = NSMutableData(capacity: sizeof(UInt16))
var buffer = UnsafeMutablePointer<UInt16>(buf!.bytes)
buffer[0] = code.byteSwapped
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
}
///used to write things to the stream in a
private func dequeueWrite(data: NSData, code: OpCode) {
if writeQueue == nil {
writeQueue = NSOperationQueue()
writeQueue!.maxConcurrentOperationCount = 1
}
writeQueue!.addOperationWithBlock {
//stream isn't ready, let's wait
var tries = 0;
while self.outputStream == nil || !self.connected {
if(tries < 5) {
sleep(1);
} else {
break;
}
tries++;
}
if !self.connected {
return
}
var offset = 2
UINT16_MAX
let bytes = UnsafeMutablePointer<UInt8>(data.bytes)
let dataLength = data.length
let frame = NSMutableData(capacity: dataLength + self.MaxFrameSize)
let buffer = UnsafeMutablePointer<UInt8>(frame!.mutableBytes)
buffer[0] = self.FinMask | code.rawValue
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
var sizeBuffer = UnsafeMutablePointer<UInt16>((buffer+offset))
sizeBuffer[0] = UInt16(dataLength).byteSwapped
offset += sizeof(UInt16)
} else {
buffer[1] = 127
var sizeBuffer = UnsafeMutablePointer<UInt64>((buffer+offset))
sizeBuffer[0] = UInt64(dataLength).byteSwapped
offset += sizeof(UInt64)
}
buffer[1] |= self.MaskMask
var maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
SecRandomCopyBytes(kSecRandomDefault, UInt(sizeof(UInt32)), maskKey)
offset += sizeof(UInt32)
for (var i = 0; i < dataLength; i++) {
buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)]
offset += 1
}
var total = 0
while true {
if self.outputStream == nil {
break
}
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
var len = self.outputStream?.write(writeBuffer, maxLength: offset-total)
if len == nil || len! < 0 {
var error: NSError?
if let streamError = self.outputStream?.streamError {
error = streamError
} else {
let errCode = InternalErrorCode.OutputStreamWriteError.rawValue
error = self.errorWithDetail("output stream error during write", code: errCode)
}
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
break
} else {
total += len!
}
if total >= offset {
break
}
}
}
}
}