merge master
This commit is contained in:
commit
560235353d
230
LICENSE
Normal file
230
LICENSE
Normal 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.
|
||||||
53
README.md
53
README.md
@ -3,12 +3,39 @@ Socket.IO-Client-Swift
|
|||||||
|
|
||||||
Socket.IO-client for Swift. Supports ws/wss/polling connections and binary. For socket.io 1.0+ and Swift 1.2.
|
Socket.IO-client for Swift. Supports ws/wss/polling connections and binary. For socket.io 1.0+ and Swift 1.2.
|
||||||
|
|
||||||
For Swift 1.1 use the master branch.
|
For Swift 1.1 use the master.
|
||||||
|
|
||||||
Installation
|
Installation
|
||||||
============
|
============
|
||||||
|
|
||||||
|
Manually (iOS 7+)
|
||||||
|
-----------------
|
||||||
1. Copy the SwiftIO folder into your Xcode project!
|
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
|
API
|
||||||
===
|
===
|
||||||
Constructor
|
Constructor
|
||||||
@ -71,6 +98,11 @@ socket.on("ackEvent") {data, ack in
|
|||||||
println("Got ackEvent")
|
println("Got ackEvent")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// data is an array
|
||||||
|
if let int = data?[1] as? Int {
|
||||||
|
println("Got int")
|
||||||
|
}
|
||||||
|
|
||||||
socket.emitWithAck("ackTest", "test").onAck {data in
|
socket.emitWithAck("ackTest", "test").onAck {data in
|
||||||
println(data?[0])
|
println(data?[0])
|
||||||
}
|
}
|
||||||
@ -84,25 +116,6 @@ socket.on("jsonTest") {data, ack in
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Event items are passed by an array
|
|
||||||
socket.on("multipleItems") {data, ack in
|
|
||||||
if data == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if let str = data![0] as? String {
|
|
||||||
println(str)
|
|
||||||
}
|
|
||||||
|
|
||||||
if let arr = data![1] as? [Int] {
|
|
||||||
println(arr)
|
|
||||||
}
|
|
||||||
|
|
||||||
if let obj = data![4] as? NSDictionary {
|
|
||||||
println(obj["test"])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Connecting
|
// Connecting
|
||||||
socket.connect()
|
socket.connect()
|
||||||
```
|
```
|
||||||
|
|||||||
19
Socket.IO-Client-Swift.podspec
Normal file
19
Socket.IO-Client-Swift.podspec
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
Pod::Spec.new do |s|
|
||||||
|
s.name = "Socket.IO-Client-Swift"
|
||||||
|
s.version = "1.1.3"
|
||||||
|
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.1.3' }
|
||||||
|
s.source_files = "SwiftIO/**/*.swift"
|
||||||
|
s.requires_arc = true
|
||||||
|
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
|
||||||
|
end
|
||||||
@ -24,10 +24,6 @@
|
|||||||
|
|
||||||
import Foundation
|
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 {
|
extension String {
|
||||||
private var length:Int {
|
private var length:Int {
|
||||||
return count(self)
|
return count(self)
|
||||||
@ -55,18 +51,22 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
"parseQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
"parseQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||||
private let handleQueue = dispatch_queue_create(
|
private let handleQueue = dispatch_queue_create(
|
||||||
"handleQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
"handleQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||||
|
private let session:NSURLSession!
|
||||||
|
private var _connected = false
|
||||||
|
private var fastUpgrade = false
|
||||||
private var forcePolling = false
|
private var forcePolling = false
|
||||||
private var pingTimer:NSTimer?
|
private var pingTimer:NSTimer?
|
||||||
private var postWait = [String]()
|
private var postWait = [String]()
|
||||||
private var _polling = true
|
private var _polling = true
|
||||||
private var probing = false
|
private var probing = false
|
||||||
private var probeWait = PollWaitQueue()
|
private var probeWait = PollWaitQueue()
|
||||||
private let session:NSURLSession!
|
|
||||||
private var waitingForPoll = false
|
private var waitingForPoll = false
|
||||||
private var waitingForPost = false
|
private var waitingForPost = false
|
||||||
private var _websocket = false
|
private var _websocket = false
|
||||||
private var websocketConnected = false
|
private var websocketConnected = false
|
||||||
var connected = false
|
var connected:Bool {
|
||||||
|
return self._connected
|
||||||
|
}
|
||||||
var pingInterval:Int?
|
var pingInterval:Int?
|
||||||
var polling:Bool {
|
var polling:Bool {
|
||||||
return self._polling
|
return self._polling
|
||||||
@ -78,19 +78,19 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
return self._websocket
|
return self._websocket
|
||||||
}
|
}
|
||||||
var ws:WebSocket?
|
var ws:WebSocket?
|
||||||
|
|
||||||
init(client:SocketIOClient, forcePolling:Bool = false) {
|
init(client:SocketIOClient, forcePolling:Bool = false) {
|
||||||
self.client = client
|
self.client = client
|
||||||
self.forcePolling = forcePolling
|
self.forcePolling = forcePolling
|
||||||
self.session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
|
self.session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
|
||||||
delegate: nil, delegateQueue: self.workQueue)
|
delegate: nil, delegateQueue: self.workQueue)
|
||||||
}
|
}
|
||||||
|
|
||||||
func close() {
|
func close() {
|
||||||
self.pingTimer?.invalidate()
|
self.pingTimer?.invalidate()
|
||||||
self.send(PacketType.CLOSE.rawValue)
|
self.send(PacketType.CLOSE.rawValue)
|
||||||
}
|
}
|
||||||
|
|
||||||
private func createBinaryDataForSend(data:NSData) -> (NSData?, String?) {
|
private func createBinaryDataForSend(data:NSData) -> (NSData?, String?) {
|
||||||
if self.websocket {
|
if self.websocket {
|
||||||
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
|
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
|
||||||
@ -102,16 +102,16 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
var str = "b4"
|
var str = "b4"
|
||||||
str += data.base64EncodedStringWithOptions(
|
str += data.base64EncodedStringWithOptions(
|
||||||
NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
|
NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
|
||||||
|
|
||||||
return (nil, str)
|
return (nil, str)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func createURLs(params:[String: AnyObject]? = nil) -> (String, String) {
|
private func createURLs(params:[String: AnyObject]? = nil) -> (String, String) {
|
||||||
var url = "\(self.client.socketURL)/socket.io/?transport="
|
var url = "\(self.client.socketURL)/socket.io/?transport="
|
||||||
var urlPolling:String
|
var urlPolling:String
|
||||||
var urlWebSocket:String
|
var urlWebSocket:String
|
||||||
|
|
||||||
if self.client.secure {
|
if self.client.secure {
|
||||||
urlPolling = "https://" + url + "polling"
|
urlPolling = "https://" + url + "polling"
|
||||||
urlWebSocket = "wss://" + url + "websocket"
|
urlWebSocket = "wss://" + url + "websocket"
|
||||||
@ -119,14 +119,14 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
urlPolling = "http://" + url + "polling"
|
urlPolling = "http://" + url + "polling"
|
||||||
urlWebSocket = "ws://" + url + "websocket"
|
urlWebSocket = "ws://" + url + "websocket"
|
||||||
}
|
}
|
||||||
|
|
||||||
if params != nil {
|
if params != nil {
|
||||||
for (key, value) in params! {
|
for (key, value) in params! {
|
||||||
let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters(
|
let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters(
|
||||||
NSCharacterSet.URLHostAllowedCharacterSet())!
|
NSCharacterSet.URLHostAllowedCharacterSet())!
|
||||||
urlPolling += "&\(keyEsc)="
|
urlPolling += "&\(keyEsc)="
|
||||||
urlWebSocket += "&\(keyEsc)="
|
urlWebSocket += "&\(keyEsc)="
|
||||||
|
|
||||||
if value is String {
|
if value is String {
|
||||||
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
|
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
|
||||||
NSCharacterSet.URLHostAllowedCharacterSet())!
|
NSCharacterSet.URLHostAllowedCharacterSet())!
|
||||||
@ -138,19 +138,34 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (urlPolling, urlWebSocket)
|
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() {
|
private func doPoll() {
|
||||||
if self.urlPolling == nil || self.websocket || self.waitingForPoll || !self.connected {
|
if self.websocket || self.waitingForPoll || !self.connected {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
|
|
||||||
req.timeoutInterval = 0.0
|
|
||||||
self.waitingForPoll = true
|
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.session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
||||||
if self == nil {
|
if self == nil {
|
||||||
return
|
return
|
||||||
@ -158,44 +173,44 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
if self!.polling {
|
if self!.polling {
|
||||||
self?.handlePollingFailed(err)
|
self?.handlePollingFailed(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// println(data)
|
// println(data)
|
||||||
|
|
||||||
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
|
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
|
||||||
// println(str)
|
// println(str)
|
||||||
|
|
||||||
dispatch_async(self!.parseQueue) {[weak self] in
|
dispatch_async(self!.parseQueue) {callback(str)}
|
||||||
if self == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self?.parsePollingMessage(str)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self?.waitingForPoll = false
|
self?.waitingForPoll = false
|
||||||
self?.doPoll()
|
|
||||||
|
if self!.fastUpgrade {
|
||||||
|
self?.doFastUpgrade()
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
self?.doPoll()
|
||||||
|
}
|
||||||
}.resume()
|
}.resume()
|
||||||
}
|
}
|
||||||
|
|
||||||
private func flushProbeWait() {
|
private func flushProbeWait() {
|
||||||
// println("flushing probe wait")
|
// println("flushing probe wait")
|
||||||
dispatch_async(self.emitQueue) {[weak self] in
|
dispatch_async(self.emitQueue) {[weak self] in
|
||||||
if self == nil {
|
if self == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for waiter in self!.probeWait {
|
for waiter in self!.probeWait {
|
||||||
waiter()
|
waiter()
|
||||||
}
|
}
|
||||||
|
|
||||||
self?.probeWait.removeAll(keepCapacity: false)
|
self?.probeWait.removeAll(keepCapacity: false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func flushWaitingForPost() {
|
private func flushWaitingForPost() {
|
||||||
if self.postWait.count == 0 || !self.connected {
|
if self.postWait.count == 0 || !self.connected {
|
||||||
return
|
return
|
||||||
@ -203,31 +218,31 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
self.flushWaitingForPostToWebSocket()
|
self.flushWaitingForPostToWebSocket()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var postStr = ""
|
var postStr = ""
|
||||||
|
|
||||||
for packet in self.postWait {
|
for packet in self.postWait {
|
||||||
let len = count(packet)
|
let len = count(packet)
|
||||||
|
|
||||||
postStr += "\(len):\(packet)"
|
postStr += "\(len):\(packet)"
|
||||||
}
|
}
|
||||||
|
|
||||||
self.postWait.removeAll(keepCapacity: false)
|
self.postWait.removeAll(keepCapacity: false)
|
||||||
|
|
||||||
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
|
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
|
||||||
|
|
||||||
req.HTTPMethod = "POST"
|
req.HTTPMethod = "POST"
|
||||||
req.setValue("application/html-text", forHTTPHeaderField: "Content-Type")
|
req.setValue("application/html-text", forHTTPHeaderField: "Content-Type")
|
||||||
|
|
||||||
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
|
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
|
||||||
allowLossyConversion: false)!
|
allowLossyConversion: false)!
|
||||||
|
|
||||||
|
|
||||||
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
|
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
|
||||||
req.HTTPBody = postData
|
req.HTTPBody = postData
|
||||||
|
|
||||||
self.waitingForPost = true
|
self.waitingForPost = true
|
||||||
|
|
||||||
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
||||||
if self == nil {
|
if self == nil {
|
||||||
return
|
return
|
||||||
@ -235,7 +250,7 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
self?.handlePollingFailed(err)
|
self?.handlePollingFailed(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
self?.waitingForPost = false
|
self?.waitingForPost = false
|
||||||
dispatch_async(self!.emitQueue) {
|
dispatch_async(self!.emitQueue) {
|
||||||
self?.flushWaitingForPost()
|
self?.flushWaitingForPost()
|
||||||
@ -243,22 +258,23 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
return
|
return
|
||||||
}}.resume()
|
}}.resume()
|
||||||
}
|
}
|
||||||
|
|
||||||
// We had packets waiting for send when we upgraded
|
// We had packets waiting for send when we upgraded
|
||||||
// Send them raw
|
// Send them raw
|
||||||
private func flushWaitingForPostToWebSocket() {
|
private func flushWaitingForPostToWebSocket() {
|
||||||
for msg in self.postWait {
|
for msg in self.postWait {
|
||||||
self.ws?.writeString(msg)
|
self.ws?.writeString(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
self.postWait.removeAll(keepCapacity: true)
|
self.postWait.removeAll(keepCapacity: true)
|
||||||
}
|
}
|
||||||
|
|
||||||
// A poll failed, tell the client about it
|
// 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?) {
|
private func handlePollingFailed(reason:NSError?) {
|
||||||
|
assert(self.polling, "Polling failed when we're not polling")
|
||||||
|
|
||||||
if !self.client.reconnecting {
|
if !self.client.reconnecting {
|
||||||
self.connected = false
|
self._connected = false
|
||||||
self.ws?.disconnect()
|
self.ws?.disconnect()
|
||||||
self.pingTimer?.invalidate()
|
self.pingTimer?.invalidate()
|
||||||
self.waitingForPoll = false
|
self.waitingForPoll = false
|
||||||
@ -266,18 +282,18 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
self.client.pollingDidFail(reason)
|
self.client.pollingDidFail(reason)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func open(opts:[String: AnyObject]? = nil) {
|
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.")
|
assert(false, "We're in a bad state, this shouldn't happen.")
|
||||||
}
|
}
|
||||||
|
|
||||||
let (urlPolling, urlWebSocket) = self.createURLs(params: opts)
|
let (urlPolling, urlWebSocket) = self.createURLs(params: opts)
|
||||||
|
|
||||||
self.urlPolling = urlPolling
|
self.urlPolling = urlPolling
|
||||||
self.urlWebSocket = urlWebSocket
|
self.urlWebSocket = urlWebSocket
|
||||||
let reqPolling = NSURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
|
let reqPolling = NSURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
|
||||||
|
|
||||||
self.session.dataTaskWithRequest(reqPolling) {[weak self] data, res, err in
|
self.session.dataTaskWithRequest(reqPolling) {[weak self] data, res, err in
|
||||||
var err2:NSError?
|
var err2:NSError?
|
||||||
if self == nil {
|
if self == nil {
|
||||||
@ -286,32 +302,31 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
self?.handlePollingFailed(err)
|
self?.handlePollingFailed(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if let dataString = NSString(data: data, encoding: NSUTF8StringEncoding) {
|
if let dataString = NSString(data: data, encoding: NSUTF8StringEncoding) {
|
||||||
var mutString = RegexMutable(dataString)
|
var mutString = RegexMutable(dataString)
|
||||||
let parsed:[String]? = mutString["(\\d*):(\\d)(\\{.*\\})?"].groups()
|
let parsed:[String]? = mutString["(\\d*):(\\d)(\\{.*\\})?"].groups()
|
||||||
|
|
||||||
if parsed == nil || parsed?.count != 4 {
|
if parsed == nil || parsed?.count != 4 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
let length = parsed![1]
|
let length = parsed![1]
|
||||||
let type = parsed![2]
|
let type = parsed![2]
|
||||||
let jsonData = parsed![3].dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
let jsonData = parsed![3].dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
||||||
|
|
||||||
if type != "0" {
|
if type != "0" {
|
||||||
NSLog("Error handshaking")
|
NSLog("Error handshaking")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
self?.connected = true
|
|
||||||
|
|
||||||
if let json = NSJSONSerialization.JSONObjectWithData(jsonData!,
|
if let json = NSJSONSerialization.JSONObjectWithData(jsonData!,
|
||||||
options: NSJSONReadingOptions.AllowFragments, error: &err2) as? NSDictionary {
|
options: NSJSONReadingOptions.AllowFragments, error: &err2) as? NSDictionary {
|
||||||
if let sid = json["sid"] as? String {
|
if let sid = json["sid"] as? String {
|
||||||
// println(json)
|
// println(json)
|
||||||
self?.sid = sid
|
self?.sid = sid
|
||||||
|
self?._connected = true
|
||||||
|
|
||||||
if !self!.forcePolling {
|
if !self!.forcePolling {
|
||||||
self?.ws = WebSocket(url: NSURL(string: urlWebSocket + "&sid=\(self!.sid)")!)
|
self?.ws = WebSocket(url: NSURL(string: urlWebSocket + "&sid=\(self!.sid)")!)
|
||||||
self?.ws?.queue = self?.handleQueue
|
self?.ws?.queue = self?.handleQueue
|
||||||
@ -322,113 +337,111 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
NSLog("Error handshaking")
|
NSLog("Error handshaking")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if let pingInterval = json["pingInterval"] as? Int {
|
if let pingInterval = json["pingInterval"] as? Int {
|
||||||
self?.pingInterval = pingInterval / 1000
|
self?.pingInterval = pingInterval / 1000
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
self?.doPoll()
|
self?.doPoll()
|
||||||
self?.startPingTimer()
|
self?.startPingTimer()
|
||||||
}}.resume()
|
}}.resume()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Translatation of engine.io-parser#decodePayload
|
// Translatation of engine.io-parser#decodePayload
|
||||||
private func parsePollingMessage(str:String) {
|
private func parsePollingMessage(str:String) {
|
||||||
if str.length == 1 {
|
if str.length == 1 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// println(str)
|
// println(str)
|
||||||
|
|
||||||
let strArray = Array(str)
|
let strArray = Array(str)
|
||||||
var length = ""
|
var length = ""
|
||||||
var n = 0
|
var n = 0
|
||||||
var msg = ""
|
var msg = ""
|
||||||
|
|
||||||
func testLength(length:String, inout n:Int) -> Bool {
|
func testLength(length:String, inout n:Int) -> Bool {
|
||||||
if let num = length.toInt() {
|
if let num = length.toInt() {
|
||||||
n = num
|
n = num
|
||||||
} else {
|
} else {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
for var i = 0, l = str.length; i < l; i = i &+ 1 {
|
for var i = 0, l = str.length; i < l; i = i &+ 1 {
|
||||||
let chr = String(strArray[i])
|
let chr = String(strArray[i])
|
||||||
|
|
||||||
if chr != ":" {
|
if chr != ":" {
|
||||||
length += chr
|
length += chr
|
||||||
} else {
|
} else {
|
||||||
if length == "" || testLength(length, &n) {
|
if length == "" || testLength(length, &n) {
|
||||||
self.handlePollingFailed(nil)
|
println("failure in parsePollingMessage")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
msg = String(strArray[i&+1...i&+n])
|
msg = String(strArray[i&+1...i&+n])
|
||||||
|
|
||||||
if let lengthInt = length.toInt() {
|
if let lengthInt = length.toInt() {
|
||||||
if lengthInt != msg.length {
|
if lengthInt != msg.length {
|
||||||
println("parsing error")
|
println("parsing error")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if msg.length != 0 {
|
if msg.length != 0 {
|
||||||
// Be sure to capture the value of the msg
|
// Be sure to capture the value of the msg
|
||||||
dispatch_async(self.handleQueue) {[weak self, msg] in
|
dispatch_async(self.handleQueue) {[weak self, msg] in
|
||||||
fixSwift = msg
|
self?.parseEngineMessage(msg)
|
||||||
if fixSwift is String {
|
return
|
||||||
self?.parseEngineMessage(fixSwift as! String)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
i += n
|
i += n
|
||||||
length = ""
|
length = ""
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func parseEngineData(data:NSData) {
|
private func parseEngineData(data:NSData) {
|
||||||
self.client.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
|
self.client.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
|
||||||
}
|
}
|
||||||
|
|
||||||
private func parseEngineMessage(var message:String) {
|
private func parseEngineMessage(var message:String) {
|
||||||
// println(message!)
|
// println(message!)
|
||||||
|
|
||||||
var strMessage = RegexMutable(message)
|
var strMessage = RegexMutable(message)
|
||||||
|
|
||||||
// We should upgrade
|
// We should upgrade
|
||||||
if strMessage == "3probe" {
|
if strMessage == "3probe" {
|
||||||
self.upgradeTransport()
|
self.upgradeTransport()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
let type = strMessage["^(\\d)"].groups()?[1]
|
let type = strMessage["^(\\d)"].groups()?[1]
|
||||||
|
|
||||||
if type != PacketType.MESSAGE.rawValue {
|
if type != PacketType.MESSAGE.rawValue {
|
||||||
// TODO Handle other packets
|
// TODO Handle other packets
|
||||||
if message.hasPrefix("b4") {
|
if message.hasPrefix("b4") {
|
||||||
// binary in base64 string
|
// binary in base64 string
|
||||||
|
|
||||||
message.removeRange(Range<String.Index>(start: message.startIndex,
|
message.removeRange(Range<String.Index>(start: message.startIndex,
|
||||||
end: advance(message.startIndex, 2)))
|
end: advance(message.startIndex, 2)))
|
||||||
|
|
||||||
if let data = NSData(base64EncodedString: message,
|
if let data = NSData(base64EncodedString: message,
|
||||||
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) {
|
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) {
|
||||||
// println("sending \(data)")
|
// println("sending \(data)")
|
||||||
self.client.parseBinaryData(data)
|
self.client.parseBinaryData(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
} else if type == PacketType.NOOP.rawValue {
|
} else if type == PacketType.NOOP.rawValue {
|
||||||
self.doPoll()
|
self.doPoll()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if message == PacketType.CLOSE.rawValue {
|
if message == PacketType.CLOSE.rawValue {
|
||||||
// do nothing
|
// do nothing
|
||||||
return
|
return
|
||||||
@ -436,42 +449,42 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
// println("Got something idk what to do with")
|
// println("Got something idk what to do with")
|
||||||
// println(messageString)
|
// println(messageString)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove message type
|
// Remove message type
|
||||||
message.removeAtIndex(message.startIndex)
|
message.removeAtIndex(message.startIndex)
|
||||||
// println("sending \(messageString)")
|
// println("sending \(messageString)")
|
||||||
|
|
||||||
self.client.parseSocketMessage(message)
|
self.client.parseSocketMessage(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
private func probeWebSocket() {
|
private func probeWebSocket() {
|
||||||
if self.websocketConnected {
|
if self.websocketConnected {
|
||||||
self.sendWebSocketMessage("probe", withType: PacketType.PING)
|
self.sendWebSocketMessage("probe", withType: PacketType.PING)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func send(msg:String, datas:[NSData]? = nil) {
|
func send(msg:String, datas:[NSData]? = nil) {
|
||||||
let _send = {[weak self] (msg:String, datas:[NSData]?) -> () -> Void in
|
let _send = {[weak self] (msg:String, datas:[NSData]?) -> () -> Void in
|
||||||
return {
|
return {
|
||||||
if self == nil || !self!.connected {
|
if self == nil || !self!.connected {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if self!.websocket {
|
if self!.websocket {
|
||||||
// println("sending ws: \(msg):\(datas)")
|
// println("sending ws: \(msg):\(datas)")
|
||||||
self?.sendWebSocketMessage(msg, withType: PacketType.MESSAGE, datas: datas)
|
self?.sendWebSocketMessage(msg, withType: PacketType.MESSAGE, datas: datas)
|
||||||
} else {
|
} else {
|
||||||
// println("sending poll: \(msg):\(datas)")
|
// println("sending poll: \(msg):\(datas)")
|
||||||
self?.sendPollMessage(msg, withType: PacketType.MESSAGE, datas: datas)
|
self?.sendPollMessage(msg, withType: PacketType.MESSAGE, datas: datas, doPoll: true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
dispatch_async(self.emitQueue) {[weak self] in
|
dispatch_async(self.emitQueue) {[weak self] in
|
||||||
if self == nil {
|
if self == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if self!.probing {
|
if self!.probing {
|
||||||
self?.probeWait.append(_send(msg, datas))
|
self?.probeWait.append(_send(msg, datas))
|
||||||
} else {
|
} else {
|
||||||
@ -479,41 +492,41 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func sendPing() {
|
func sendPing() {
|
||||||
if self.websocket {
|
if self.websocket {
|
||||||
self.sendWebSocketMessage("", withType: PacketType.PING)
|
self.sendWebSocketMessage("", withType: PacketType.PING)
|
||||||
} else {
|
} else {
|
||||||
self.sendPollMessage("", withType: PacketType.PING)
|
self.sendPollMessage("", withType: PacketType.PING, doPoll: false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func sendPollMessage(msg:String, withType type:PacketType, datas:[NSData]? = nil) {
|
private func sendPollMessage(msg:String, withType type:PacketType,
|
||||||
// println("Sending: poll: \(msg) as type: \(type.rawValue)")
|
datas:[NSData]? = nil, doPoll poll:Bool) {
|
||||||
let strMsg = "\(type.rawValue)\(msg)"
|
// println("Sending poll: \(msg) as type: \(type.rawValue)")
|
||||||
|
let strMsg = "\(type.rawValue)\(msg)"
|
||||||
self.postWait.append(strMsg)
|
|
||||||
|
self.postWait.append(strMsg)
|
||||||
if datas != nil {
|
|
||||||
for data in datas! {
|
if datas != nil {
|
||||||
let (nilData, b64Data) = self.createBinaryDataForSend(data)
|
for data in datas! {
|
||||||
|
let (nilData, b64Data) = self.createBinaryDataForSend(data)
|
||||||
self.postWait.append(b64Data!)
|
|
||||||
|
self.postWait.append(b64Data!)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !self.waitingForPoll && self.waitingForPost && poll {
|
||||||
|
self.doPoll()
|
||||||
|
} else {
|
||||||
|
self.flushWaitingForPost()
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if waitingForPost {
|
|
||||||
self.doPoll()
|
|
||||||
return
|
|
||||||
} else {
|
|
||||||
self.flushWaitingForPost()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private func sendWebSocketMessage(str:String, withType type:PacketType, datas:[NSData]? = nil) {
|
private func sendWebSocketMessage(str:String, withType type:PacketType, datas:[NSData]? = nil) {
|
||||||
// println("Sending: ws: \(str) as type: \(type.rawValue)")
|
// println("Sending ws: \(str) as type: \(type.rawValue)")
|
||||||
self.ws?.writeString("\(type.rawValue)\(str)")
|
self.ws?.writeString("\(type.rawValue)\(str)")
|
||||||
|
|
||||||
if datas != nil {
|
if datas != nil {
|
||||||
for data in datas! {
|
for data in datas! {
|
||||||
let (data, nilString) = self.createBinaryDataForSend(data)
|
let (data, nilString) = self.createBinaryDataForSend(data)
|
||||||
@ -523,44 +536,42 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Starts the ping timer
|
// Starts the ping timer
|
||||||
private func startPingTimer() {
|
private func startPingTimer() {
|
||||||
if self.pingInterval == nil {
|
if self.pingInterval == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
self.pingTimer?.invalidate()
|
self.pingTimer?.invalidate()
|
||||||
dispatch_async(dispatch_get_main_queue()) {
|
dispatch_async(dispatch_get_main_queue()) {
|
||||||
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(self.pingInterval!), target: self,
|
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(self.pingInterval!), target: self,
|
||||||
selector: Selector("sendPing"), userInfo: nil, repeats: true)
|
selector: Selector("sendPing"), userInfo: nil, repeats: true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func upgradeTransport() {
|
private func upgradeTransport() {
|
||||||
if self.websocketConnected {
|
if self.websocketConnected {
|
||||||
|
// Do a fast upgrade
|
||||||
|
self.fastUpgrade = true
|
||||||
self.probing = false
|
self.probing = false
|
||||||
self._websocket = true
|
self.sendPollMessage("", withType: PacketType.NOOP, doPoll: false)
|
||||||
self.waitingForPoll = false
|
|
||||||
self._polling = false
|
|
||||||
self.sendWebSocketMessage("", withType: PacketType.UPGRADE)
|
|
||||||
self.flushProbeWait()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func websocketDidConnect(socket:WebSocket) {
|
func websocketDidConnect(socket:WebSocket) {
|
||||||
self.websocketConnected = true
|
self.websocketConnected = true
|
||||||
self.probing = true
|
self.probing = true
|
||||||
self.probeWebSocket()
|
self.probeWebSocket()
|
||||||
}
|
}
|
||||||
|
|
||||||
func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
|
func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
|
||||||
self.websocketConnected = false
|
self.websocketConnected = false
|
||||||
self.probing = false
|
self.probing = false
|
||||||
|
|
||||||
if self.websocket {
|
if self.websocket {
|
||||||
self.pingTimer?.invalidate()
|
self.pingTimer?.invalidate()
|
||||||
self.connected = false
|
self._connected = false
|
||||||
self._websocket = false
|
self._websocket = false
|
||||||
self._polling = true
|
self._polling = true
|
||||||
self.client.webSocketDidCloseWithCode(1, reason: "Socket Disconnect", wasClean: true)
|
self.client.webSocketDidCloseWithCode(1, reason: "Socket Disconnect", wasClean: true)
|
||||||
@ -568,12 +579,12 @@ class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
self.flushProbeWait()
|
self.flushProbeWait()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func websocketDidReceiveMessage(socket:WebSocket, text:String) {
|
func websocketDidReceiveMessage(socket:WebSocket, text:String) {
|
||||||
self.parseEngineMessage(text)
|
self.parseEngineMessage(text)
|
||||||
}
|
}
|
||||||
|
|
||||||
func websocketDidReceiveData(socket:WebSocket, data:NSData) {
|
func websocketDidReceiveData(socket:WebSocket, data:NSData) {
|
||||||
self.parseEngineData(data)
|
self.parseEngineData(data)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -56,51 +56,51 @@ public class SocketIOClient: NSObject {
|
|||||||
return self._secure
|
return self._secure
|
||||||
}
|
}
|
||||||
var sid:String?
|
var sid:String?
|
||||||
|
|
||||||
public init(socketURL:String, opts:[String: AnyObject]? = nil) {
|
public init(socketURL:String, opts:[String: AnyObject]? = nil) {
|
||||||
var mutURL = RegexMutable(socketURL)
|
var mutURL = RegexMutable(socketURL)
|
||||||
|
|
||||||
if mutURL["https://"].matches().count != 0 {
|
if mutURL["https://"].matches().count != 0 {
|
||||||
self._secure = true
|
self._secure = true
|
||||||
}
|
}
|
||||||
|
|
||||||
mutURL = mutURL["http://"] ~= ""
|
mutURL = mutURL["http://"] ~= ""
|
||||||
mutURL = mutURL["https://"] ~= ""
|
mutURL = mutURL["https://"] ~= ""
|
||||||
|
|
||||||
self.socketURL = mutURL
|
self.socketURL = mutURL
|
||||||
|
|
||||||
// Set options
|
// Set options
|
||||||
if opts != nil {
|
if opts != nil {
|
||||||
if let reconnects = opts!["reconnects"] as? Bool {
|
if let reconnects = opts!["reconnects"] as? Bool {
|
||||||
self.reconnects = reconnects
|
self.reconnects = reconnects
|
||||||
}
|
}
|
||||||
|
|
||||||
if let reconnectAttempts = opts!["reconnectAttempts"] as? Int {
|
if let reconnectAttempts = opts!["reconnectAttempts"] as? Int {
|
||||||
self.reconnectAttempts = reconnectAttempts
|
self.reconnectAttempts = reconnectAttempts
|
||||||
} else {
|
} else {
|
||||||
self.reconnectAttempts = -1
|
self.reconnectAttempts = -1
|
||||||
}
|
}
|
||||||
|
|
||||||
if let reconnectWait = opts!["reconnectWait"] as? Int {
|
if let reconnectWait = opts!["reconnectWait"] as? Int {
|
||||||
self.reconnectWait = abs(reconnectWait)
|
self.reconnectWait = abs(reconnectWait)
|
||||||
}
|
}
|
||||||
|
|
||||||
if let nsp = opts!["nsp"] as? String {
|
if let nsp = opts!["nsp"] as? String {
|
||||||
self.nsp = nsp
|
self.nsp = nsp
|
||||||
}
|
}
|
||||||
|
|
||||||
if let polling = opts!["forcePolling"] as? Bool {
|
if let polling = opts!["forcePolling"] as? Bool {
|
||||||
self.forcePolling = polling
|
self.forcePolling = polling
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
self.reconnectAttempts = -1
|
self.reconnectAttempts = -1
|
||||||
}
|
}
|
||||||
|
|
||||||
super.init()
|
super.init()
|
||||||
|
|
||||||
self.engine = SocketEngine(client: self, forcePolling: self.forcePolling)
|
self.engine = SocketEngine(client: self, forcePolling: self.forcePolling)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Closes the socket
|
// Closes the socket
|
||||||
public func close() {
|
public func close() {
|
||||||
self.closed = true
|
self.closed = true
|
||||||
@ -109,30 +109,30 @@ public class SocketIOClient: NSObject {
|
|||||||
self.reconnecting = false
|
self.reconnecting = false
|
||||||
self.engine?.close()
|
self.engine?.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Connects to the server
|
// Connects to the server
|
||||||
public func connect() {
|
public func connect() {
|
||||||
if self.closed {
|
if self.closed {
|
||||||
println("Warning! This socket was previously closed. This might be dangerous!")
|
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
|
// Connect to the server using params
|
||||||
public func connectWithParams(params:[String: AnyObject]) {
|
public func connectWithParams(params:[String: AnyObject]) {
|
||||||
if self.closed {
|
if self.closed {
|
||||||
println("Warning! This socket was previously closed. This might be dangerous!")
|
println("Warning! This socket was previously closed. This might be dangerous!")
|
||||||
self.closed = false
|
self.closed = false
|
||||||
}
|
}
|
||||||
|
|
||||||
self.params = params
|
self.params = params
|
||||||
self.paramConnect = true
|
self.paramConnect = true
|
||||||
|
|
||||||
self.engine?.open(opts: params)
|
self.engine?.open(opts: params)
|
||||||
}
|
}
|
||||||
|
|
||||||
func didConnect() {
|
func didConnect() {
|
||||||
self.closed = false
|
self.closed = false
|
||||||
self.connected = true
|
self.connected = true
|
||||||
@ -141,10 +141,11 @@ public class SocketIOClient: NSObject {
|
|||||||
self.currentReconnectAttempt = 0
|
self.currentReconnectAttempt = 0
|
||||||
self.reconnectTimer?.invalidate()
|
self.reconnectTimer?.invalidate()
|
||||||
self.reconnectTimer = nil
|
self.reconnectTimer = nil
|
||||||
|
self.sid = self.engine?.sid
|
||||||
|
|
||||||
self.handleEvent("connect", data: nil, isInternalMessage: false)
|
self.handleEvent("connect", data: nil, isInternalMessage: false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Server wants us to die
|
// Server wants us to die
|
||||||
func didForceClose() {
|
func didForceClose() {
|
||||||
self.closed = true
|
self.closed = true
|
||||||
@ -154,7 +155,7 @@ public class SocketIOClient: NSObject {
|
|||||||
self.reconnecting = false
|
self.reconnecting = false
|
||||||
self.handleEvent("disconnect", data: "closed", isInternalMessage: true)
|
self.handleEvent("disconnect", data: "closed", isInternalMessage: true)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sends a message with multiple args
|
// Sends a message with multiple args
|
||||||
// If a message contains binary we have to send those
|
// If a message contains binary we have to send those
|
||||||
// seperately.
|
// seperately.
|
||||||
@ -162,13 +163,13 @@ public class SocketIOClient: NSObject {
|
|||||||
if !self.connected {
|
if !self.connected {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
dispatch_async(self.emitQueue) {[weak self] in
|
dispatch_async(self.emitQueue) {[weak self] in
|
||||||
self?._emit(event, args)
|
self?._emit(event, args)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Objc doesn't have variadics
|
// Objc doesn't have variadics
|
||||||
public func emitObjc(event:String, _ args:[AnyObject]) {
|
public func emitObjc(event:String, _ args:[AnyObject]) {
|
||||||
self.emit(event, args)
|
self.emit(event, args)
|
||||||
@ -178,33 +179,33 @@ public class SocketIOClient: NSObject {
|
|||||||
if !self.connected {
|
if !self.connected {
|
||||||
return SocketAckHandler(event: "fail")
|
return SocketAckHandler(event: "fail")
|
||||||
}
|
}
|
||||||
|
|
||||||
self.currentAck++
|
self.currentAck++
|
||||||
let ackHandler = SocketAckHandler(event: event, ackNum: self.currentAck)
|
let ackHandler = SocketAckHandler(event: event, ackNum: self.currentAck)
|
||||||
self.ackHandlers.append(ackHandler)
|
self.ackHandlers.append(ackHandler)
|
||||||
|
|
||||||
dispatch_async(self.emitQueue) {[weak self] in
|
dispatch_async(self.emitQueue) {[weak self] in
|
||||||
self?._emit(event, args, ack: true)
|
self?._emit(event, args, ack: true)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
return ackHandler
|
return ackHandler
|
||||||
}
|
}
|
||||||
|
|
||||||
public func emitWithAckObjc(event:String, _ args:[AnyObject]) -> SocketAckHandler {
|
public func emitWithAckObjc(event:String, _ args:[AnyObject]) -> SocketAckHandler {
|
||||||
return self.emitWithAck(event, args)
|
return self.emitWithAck(event, args)
|
||||||
}
|
}
|
||||||
|
|
||||||
private func _emit(event:String, _ args:[AnyObject], ack:Bool = false) {
|
private func _emit(event:String, _ args:[AnyObject], ack:Bool = false) {
|
||||||
var frame:SocketEvent
|
var frame:SocketEvent
|
||||||
var str:String
|
var str:String
|
||||||
|
|
||||||
let (items, hasBinary, emitDatas) = SocketIOClient.parseEmitArgs(args)
|
let (items, hasBinary, emitDatas) = SocketIOClient.parseEmitArgs(args)
|
||||||
|
|
||||||
if !self.connected {
|
if !self.connected {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if hasBinary {
|
if hasBinary {
|
||||||
if !ack {
|
if !ack {
|
||||||
str = SocketEvent.createMessageForEvent(event, withArgs: items,
|
str = SocketEvent.createMessageForEvent(event, withArgs: items,
|
||||||
@ -213,7 +214,7 @@ public class SocketIOClient: NSObject {
|
|||||||
str = SocketEvent.createMessageForEvent(event, withArgs: items,
|
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: self.currentAck)
|
||||||
}
|
}
|
||||||
|
|
||||||
self.engine?.send(str, datas: emitDatas)
|
self.engine?.send(str, datas: emitDatas)
|
||||||
} else {
|
} else {
|
||||||
if !ack {
|
if !ack {
|
||||||
@ -223,21 +224,21 @@ public class SocketIOClient: NSObject {
|
|||||||
str = SocketEvent.createMessageForEvent(event, withArgs: items, hasBinary: false,
|
str = SocketEvent.createMessageForEvent(event, withArgs: items, hasBinary: false,
|
||||||
withDatas: 0, toNamespace: self.nsp, wantsAck: self.currentAck)
|
withDatas: 0, toNamespace: self.nsp, wantsAck: self.currentAck)
|
||||||
}
|
}
|
||||||
|
|
||||||
self.engine?.send(str)
|
self.engine?.send(str)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If the server wants to know that the client received data
|
// If the server wants to know that the client received data
|
||||||
internal func emitAck(ack:Int, withData data:[AnyObject]?, withAckType ackType:Int) {
|
internal func emitAck(ack:Int, withData data:[AnyObject]?, withAckType ackType:Int) {
|
||||||
dispatch_async(self.ackQueue) {[weak self] in
|
dispatch_async(self.ackQueue) {[weak self] in
|
||||||
if self == nil || !self!.connected || data == nil {
|
if self == nil || !self!.connected || data == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
let (items, hasBinary, emitDatas) = SocketIOClient.parseEmitArgs(data!)
|
let (items, hasBinary, emitDatas) = SocketIOClient.parseEmitArgs(data!)
|
||||||
var str:String
|
var str:String
|
||||||
|
|
||||||
if !hasBinary {
|
if !hasBinary {
|
||||||
if self?.nsp == nil {
|
if self?.nsp == nil {
|
||||||
str = SocketEvent.createAck(ack, withArgs: items,
|
str = SocketEvent.createAck(ack, withArgs: items,
|
||||||
@ -246,7 +247,7 @@ public class SocketIOClient: NSObject {
|
|||||||
str = SocketEvent.createAck(ack, withArgs: items,
|
str = SocketEvent.createAck(ack, withArgs: items,
|
||||||
withAckType: 3, withNsp: self!.nsp!)
|
withAckType: 3, withNsp: self!.nsp!)
|
||||||
}
|
}
|
||||||
|
|
||||||
self?.engine?.send(str)
|
self?.engine?.send(str)
|
||||||
} else {
|
} else {
|
||||||
if self?.nsp == nil {
|
if self?.nsp == nil {
|
||||||
@ -256,12 +257,12 @@ public class SocketIOClient: NSObject {
|
|||||||
str = SocketEvent.createAck(ack, withArgs: items,
|
str = SocketEvent.createAck(ack, withArgs: items,
|
||||||
withAckType: 6, withNsp: self!.nsp!, withBinary: emitDatas.count)
|
withAckType: 6, withNsp: self!.nsp!, withBinary: emitDatas.count)
|
||||||
}
|
}
|
||||||
|
|
||||||
self?.engine?.send(str, datas: emitDatas)
|
self?.engine?.send(str, datas: emitDatas)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Called when the socket gets an ack for something it sent
|
// Called when the socket gets an ack for something it sent
|
||||||
private func handleAck(ack:Int, data:AnyObject?) {
|
private func handleAck(ack:Int, data:AnyObject?) {
|
||||||
self.ackHandlers = self.ackHandlers.filter {handler in
|
self.ackHandlers = self.ackHandlers.filter {handler in
|
||||||
@ -275,12 +276,12 @@ public class SocketIOClient: NSObject {
|
|||||||
} else {
|
} else {
|
||||||
handler.executeAck(nil)
|
handler.executeAck(nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handles events
|
// Handles events
|
||||||
public 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) {
|
wantsAck ack:Int? = nil, withAckType ackType:Int = 3) {
|
||||||
@ -288,7 +289,7 @@ public class SocketIOClient: NSObject {
|
|||||||
if !self.connected && !isInternalMessage {
|
if !self.connected && !isInternalMessage {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
dispatch_async(dispatch_get_main_queue()) {[weak self] in
|
dispatch_async(dispatch_get_main_queue()) {[weak self] in
|
||||||
self?.anyHandler?((event, data))
|
self?.anyHandler?((event, data))
|
||||||
return
|
return
|
||||||
@ -303,15 +304,15 @@ public class SocketIOClient: NSObject {
|
|||||||
handler.executeCallback(data as? NSArray)
|
handler.executeCallback(data as? NSArray)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
// Trying to do a ternary expression in the executeCallback method
|
// Trying to do a ternary expression in the executeCallback method
|
||||||
// seemed to crash Swift
|
// seemed to crash Swift
|
||||||
var dataArr:NSArray? = nil
|
var dataArr:NSArray? = nil
|
||||||
|
|
||||||
if let data:AnyObject = data {
|
if let data:AnyObject = data {
|
||||||
dataArr = [data]
|
dataArr = [data]
|
||||||
}
|
}
|
||||||
|
|
||||||
if ack != nil {
|
if ack != nil {
|
||||||
handler.executeCallback(dataArr, withAck: ack!,
|
handler.executeCallback(dataArr, withAck: ack!,
|
||||||
withAckType: ackType, withSocket: self)
|
withAckType: ackType, withSocket: self)
|
||||||
@ -322,49 +323,49 @@ public class SocketIOClient: NSObject {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Should be removed and moved to SocketEngine
|
// Should be removed and moved to SocketEngine
|
||||||
func joinNamespace() {
|
func joinNamespace() {
|
||||||
if self.nsp != nil {
|
if self.nsp != nil {
|
||||||
self.engine?.send("0/\(self.nsp!)")
|
self.engine?.send("0/\(self.nsp!)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Adds handler for an event
|
// Adds handler for an event
|
||||||
public func on(name:String, callback:NormalCallback) {
|
public func on(name:String, callback:NormalCallback) {
|
||||||
let handler = SocketEventHandler(event: name, callback: callback)
|
let handler = SocketEventHandler(event: name, callback: callback)
|
||||||
self.handlers.append(handler)
|
self.handlers.append(handler)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Adds a handler for any event
|
// Adds a handler for any event
|
||||||
public func onAny(handler:(AnyHandler) -> Void) {
|
public func onAny(handler:(AnyHandler) -> Void) {
|
||||||
self.anyHandler = handler
|
self.anyHandler = handler
|
||||||
}
|
}
|
||||||
|
|
||||||
// Opens the connection to the socket
|
// Opens the connection to the socket
|
||||||
public func open() {
|
public func open() {
|
||||||
self.connect()
|
self.connect()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse an NSArray looking for binary data
|
// Parse an NSArray looking for binary data
|
||||||
private class func parseArray(arr:NSArray, var currentPlaceholder:Int) -> (NSArray, Bool, [NSData]) {
|
private class func parseArray(arr:NSArray, var currentPlaceholder:Int) -> (NSArray, Bool, [NSData]) {
|
||||||
var replacementArr = [AnyObject](count: arr.count, repeatedValue: 1)
|
var replacementArr = [AnyObject](count: arr.count, repeatedValue: 1)
|
||||||
var hasBinary = false
|
var hasBinary = false
|
||||||
var arrayDatas = [NSData]()
|
var arrayDatas = [NSData]()
|
||||||
|
|
||||||
for g in 0..<arr.count {
|
for g in 0..<arr.count {
|
||||||
if arr[g] is NSData {
|
if arr[g] is NSData {
|
||||||
hasBinary = true
|
hasBinary = true
|
||||||
currentPlaceholder++
|
currentPlaceholder++
|
||||||
let sendData = arr[g] as! NSData
|
let sendData = arr[g] as! NSData
|
||||||
|
|
||||||
arrayDatas.append(sendData)
|
arrayDatas.append(sendData)
|
||||||
replacementArr[g] = ["_placeholder": true,
|
replacementArr[g] = ["_placeholder": true,
|
||||||
"num": currentPlaceholder]
|
"num": currentPlaceholder]
|
||||||
} else if let dict = arr[g] as? NSDictionary {
|
} else if let dict = arr[g] as? NSDictionary {
|
||||||
let (nestDict, hadBinary, dictArrs) = self.parseNSDictionary(dict,
|
let (nestDict, hadBinary, dictArrs) = self.parseNSDictionary(dict,
|
||||||
currentPlaceholder: currentPlaceholder)
|
currentPlaceholder: currentPlaceholder)
|
||||||
|
|
||||||
if hadBinary {
|
if hadBinary {
|
||||||
hasBinary = true
|
hasBinary = true
|
||||||
currentPlaceholder += dictArrs.count
|
currentPlaceholder += dictArrs.count
|
||||||
@ -377,7 +378,7 @@ public class SocketIOClient: NSObject {
|
|||||||
// Recursive
|
// Recursive
|
||||||
let (nested, hadBinary, nestDatas) = self.parseArray(nestArr,
|
let (nested, hadBinary, nestDatas) = self.parseArray(nestArr,
|
||||||
currentPlaceholder: currentPlaceholder)
|
currentPlaceholder: currentPlaceholder)
|
||||||
|
|
||||||
if hadBinary {
|
if hadBinary {
|
||||||
hasBinary = true
|
hasBinary = true
|
||||||
currentPlaceholder += nestDatas.count
|
currentPlaceholder += nestDatas.count
|
||||||
@ -390,35 +391,35 @@ public class SocketIOClient: NSObject {
|
|||||||
replacementArr[g] = arr[g]
|
replacementArr[g] = arr[g]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (replacementArr, hasBinary, arrayDatas)
|
return (replacementArr, hasBinary, arrayDatas)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parses data for events
|
// Parses data for events
|
||||||
class func parseData(data:String?) -> AnyObject? {
|
class func parseData(data:String?) -> AnyObject? {
|
||||||
if data == nil {
|
if data == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var err:NSError?
|
var err:NSError?
|
||||||
let stringData = data!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
let stringData = data!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
||||||
let parsed:AnyObject? = NSJSONSerialization.JSONObjectWithData(stringData!,
|
let parsed:AnyObject? = NSJSONSerialization.JSONObjectWithData(stringData!,
|
||||||
options: NSJSONReadingOptions.AllowFragments, error: &err)
|
options: NSJSONReadingOptions.AllowFragments, error: &err)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// println(err)
|
// println(err)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return parsed
|
return parsed
|
||||||
}
|
}
|
||||||
|
|
||||||
private class func parseEmitArgs(args:[AnyObject]) -> ([AnyObject], Bool, [NSData]) {
|
private class func parseEmitArgs(args:[AnyObject]) -> ([AnyObject], Bool, [NSData]) {
|
||||||
var items = [AnyObject](count: args.count, repeatedValue: 1)
|
var items = [AnyObject](count: args.count, repeatedValue: 1)
|
||||||
var currentPlaceholder = -1
|
var currentPlaceholder = -1
|
||||||
var hasBinary = false
|
var hasBinary = false
|
||||||
var emitDatas = [NSData]()
|
var emitDatas = [NSData]()
|
||||||
|
|
||||||
for i in 0..<args.count {
|
for i in 0..<args.count {
|
||||||
if let dict = args[i] as? NSDictionary {
|
if let dict = args[i] as? NSDictionary {
|
||||||
// Check for binary data
|
// Check for binary data
|
||||||
@ -426,7 +427,7 @@ public class SocketIOClient: NSObject {
|
|||||||
currentPlaceholder: currentPlaceholder)
|
currentPlaceholder: currentPlaceholder)
|
||||||
if hadBinary {
|
if hadBinary {
|
||||||
currentPlaceholder += binaryDatas.count
|
currentPlaceholder += binaryDatas.count
|
||||||
|
|
||||||
emitDatas.extend(binaryDatas)
|
emitDatas.extend(binaryDatas)
|
||||||
hasBinary = true
|
hasBinary = true
|
||||||
items[i] = newDict
|
items[i] = newDict
|
||||||
@ -437,15 +438,15 @@ public class SocketIOClient: NSObject {
|
|||||||
// arg is array, check for binary
|
// arg is array, check for binary
|
||||||
let (replace, hadData, newDatas) = SocketIOClient.parseArray(arr,
|
let (replace, hadData, newDatas) = SocketIOClient.parseArray(arr,
|
||||||
currentPlaceholder: currentPlaceholder)
|
currentPlaceholder: currentPlaceholder)
|
||||||
|
|
||||||
if hadData {
|
if hadData {
|
||||||
hasBinary = true
|
hasBinary = true
|
||||||
currentPlaceholder += newDatas.count
|
currentPlaceholder += newDatas.count
|
||||||
|
|
||||||
for data in newDatas {
|
for data in newDatas {
|
||||||
emitDatas.append(data)
|
emitDatas.append(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
items[i] = replace
|
items[i] = replace
|
||||||
} else {
|
} else {
|
||||||
items[i] = arr
|
items[i] = arr
|
||||||
@ -453,7 +454,7 @@ public class SocketIOClient: NSObject {
|
|||||||
} else if let binaryData = args[i] as? NSData {
|
} else if let binaryData = args[i] as? NSData {
|
||||||
// args is just binary
|
// args is just binary
|
||||||
hasBinary = true
|
hasBinary = true
|
||||||
|
|
||||||
currentPlaceholder++
|
currentPlaceholder++
|
||||||
items[i] = ["_placeholder": true, "num": currentPlaceholder]
|
items[i] = ["_placeholder": true, "num": currentPlaceholder]
|
||||||
emitDatas.append(binaryData)
|
emitDatas.append(binaryData)
|
||||||
@ -461,16 +462,16 @@ public class SocketIOClient: NSObject {
|
|||||||
items[i] = args[i]
|
items[i] = args[i]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (items, hasBinary, emitDatas)
|
return (items, hasBinary, emitDatas)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parses a NSDictionary, looking for NSData objects
|
// Parses a NSDictionary, looking for NSData objects
|
||||||
private class func parseNSDictionary(dict:NSDictionary, var currentPlaceholder:Int) -> (NSDictionary, Bool, [NSData]) {
|
private class func parseNSDictionary(dict:NSDictionary, var currentPlaceholder:Int) -> (NSDictionary, Bool, [NSData]) {
|
||||||
var returnDict = NSMutableDictionary()
|
var returnDict = NSMutableDictionary()
|
||||||
var hasBinary = false
|
var hasBinary = false
|
||||||
var returnDatas = [NSData]()
|
var returnDatas = [NSData]()
|
||||||
|
|
||||||
for (key, value) in dict {
|
for (key, value) in dict {
|
||||||
if let binaryData = value as? NSData {
|
if let binaryData = value as? NSData {
|
||||||
currentPlaceholder++
|
currentPlaceholder++
|
||||||
@ -479,7 +480,7 @@ public class SocketIOClient: NSObject {
|
|||||||
returnDict[key as! String] = ["_placeholder": true, "num": currentPlaceholder++]
|
returnDict[key as! String] = ["_placeholder": true, "num": currentPlaceholder++]
|
||||||
} else if let arr = value as? NSArray {
|
} else if let arr = value as? NSArray {
|
||||||
let (replace, hadBinary, arrDatas) = self.parseArray(arr, currentPlaceholder: currentPlaceholder)
|
let (replace, hadBinary, arrDatas) = self.parseArray(arr, currentPlaceholder: currentPlaceholder)
|
||||||
|
|
||||||
if hadBinary {
|
if hadBinary {
|
||||||
hasBinary = true
|
hasBinary = true
|
||||||
returnDict[key as! String] = replace
|
returnDict[key as! String] = replace
|
||||||
@ -491,7 +492,7 @@ public class SocketIOClient: NSObject {
|
|||||||
} else if let dict = value as? NSDictionary {
|
} else if let dict = value as? NSDictionary {
|
||||||
// Recursive
|
// Recursive
|
||||||
let (nestDict, hadBinary, nestDatas) = self.parseNSDictionary(dict, currentPlaceholder: currentPlaceholder)
|
let (nestDict, hadBinary, nestDatas) = self.parseNSDictionary(dict, currentPlaceholder: currentPlaceholder)
|
||||||
|
|
||||||
if hadBinary {
|
if hadBinary {
|
||||||
hasBinary = true
|
hasBinary = true
|
||||||
returnDict[key as! String] = nestDict
|
returnDict[key as! String] = nestDict
|
||||||
@ -504,14 +505,14 @@ public class SocketIOClient: NSObject {
|
|||||||
returnDict[key as! String] = value
|
returnDict[key as! String] = value
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (returnDict, hasBinary, returnDatas)
|
return (returnDict, hasBinary, returnDatas)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parses messages recieved
|
// Parses messages recieved
|
||||||
internal func parseSocketMessage(stringMessage:String) {
|
internal func parseSocketMessage(stringMessage:String) {
|
||||||
// println(message!)
|
// println(message!)
|
||||||
|
|
||||||
// Check for successful namepsace connect
|
// Check for successful namepsace connect
|
||||||
if self.nsp != nil {
|
if self.nsp != nil {
|
||||||
if stringMessage == "0/\(self.nsp!)" {
|
if stringMessage == "0/\(self.nsp!)" {
|
||||||
@ -519,7 +520,7 @@ public class SocketIOClient: NSObject {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if stringMessage == "0" {
|
if stringMessage == "0" {
|
||||||
if self.nsp != nil {
|
if self.nsp != nil {
|
||||||
// Join namespace
|
// Join namespace
|
||||||
@ -532,20 +533,20 @@ public class SocketIOClient: NSObject {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var mutMessage = RegexMutable(stringMessage)
|
var mutMessage = RegexMutable(stringMessage)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Begin check for message
|
Begin check for message
|
||||||
**/
|
**/
|
||||||
let messageGroups = mutMessage["(\\d*)\\/?(\\w*)?,?(\\d*)?(\\[.*\\])?"].groups()
|
let messageGroups = mutMessage["(\\d*)\\/?(\\w*)?,?(\\d*)?(\\[.*\\])?"].groups()
|
||||||
|
|
||||||
if messageGroups[1].hasPrefix("2") {
|
if messageGroups[1].hasPrefix("2") {
|
||||||
var mesNum = messageGroups[1]
|
var mesNum = messageGroups[1]
|
||||||
var ackNum:String
|
var ackNum:String
|
||||||
var namespace:String?
|
var namespace:String?
|
||||||
var messagePart:String!
|
var messagePart:String!
|
||||||
|
|
||||||
if messageGroups[3] != "" {
|
if messageGroups[3] != "" {
|
||||||
ackNum = messageGroups[3]
|
ackNum = messageGroups[3]
|
||||||
} else {
|
} else {
|
||||||
@ -553,25 +554,25 @@ public class SocketIOClient: NSObject {
|
|||||||
mesNum.replaceRange(range, with: "")
|
mesNum.replaceRange(range, with: "")
|
||||||
ackNum = mesNum
|
ackNum = mesNum
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace = messageGroups[2]
|
namespace = messageGroups[2]
|
||||||
messagePart = messageGroups[4]
|
messagePart = messageGroups[4]
|
||||||
|
|
||||||
if namespace == "" && self.nsp != nil {
|
if namespace == "" && self.nsp != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
let messageInternals = RegexMutable(messagePart)["\\[\"(.*?)\",(.*?)?\\]$"].groups()
|
let messageInternals = RegexMutable(messagePart)["\\[\"(.*?)\",(.*?)?\\]$"].groups()
|
||||||
if messageInternals != nil && messageInternals.count > 2 {
|
if messageInternals != nil && messageInternals.count > 2 {
|
||||||
let event = messageInternals[1]
|
let event = messageInternals[1]
|
||||||
var data:String?
|
var data:String?
|
||||||
|
|
||||||
if messageInternals[2] == "" {
|
if messageInternals[2] == "" {
|
||||||
data = nil
|
data = nil
|
||||||
} else {
|
} else {
|
||||||
data = messageInternals[2]
|
data = messageInternals[2]
|
||||||
}
|
}
|
||||||
|
|
||||||
// It would be nice if socket.io only allowed one thing
|
// It would be nice if socket.io only allowed one thing
|
||||||
// per message, but alas, it doesn't.
|
// per message, but alas, it doesn't.
|
||||||
if let parsed:AnyObject = SocketIOClient.parseData(data) {
|
if let parsed:AnyObject = SocketIOClient.parseData(data) {
|
||||||
@ -600,7 +601,7 @@ public class SocketIOClient: NSObject {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for no item event
|
// Check for no item event
|
||||||
let noItemMessage = RegexMutable(messagePart)["\\[\"(.*?)\"]$"].groups()
|
let noItemMessage = RegexMutable(messagePart)["\\[\"(.*?)\"]$"].groups()
|
||||||
if noItemMessage != nil && noItemMessage.count == 2 {
|
if noItemMessage != nil && noItemMessage.count == 2 {
|
||||||
@ -618,135 +619,133 @@ public class SocketIOClient: NSObject {
|
|||||||
let arr = Array(messageGroups[1])
|
let arr = Array(messageGroups[1])
|
||||||
var ackNum:String
|
var ackNum:String
|
||||||
let nsp = messageGroups[2]
|
let nsp = messageGroups[2]
|
||||||
|
|
||||||
if nsp == "" && self.nsp != nil {
|
if nsp == "" && self.nsp != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if nsp == "" {
|
if nsp == "" {
|
||||||
ackNum = String(arr[1...arr.count-1])
|
ackNum = String(arr[1...arr.count-1])
|
||||||
} else {
|
} else {
|
||||||
ackNum = messageGroups[3]
|
ackNum = messageGroups[3]
|
||||||
}
|
}
|
||||||
|
|
||||||
let ackData:AnyObject? = SocketIOClient.parseData(messageGroups[4])
|
let ackData:AnyObject? = SocketIOClient.parseData(messageGroups[4])
|
||||||
self.handleAck(ackNum.toInt()!, data: ackData)
|
self.handleAck(ackNum.toInt()!, data: ackData)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
End Check for message
|
End Check for message
|
||||||
**/
|
**/
|
||||||
|
|
||||||
// Check for message with binary placeholders
|
// Check for message with binary placeholders
|
||||||
self.parseBinaryMessage(message: stringMessage)
|
self.parseBinaryMessage(message: stringMessage)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tries to parse a message that contains binary
|
// Tries to parse a message that contains binary
|
||||||
private func parseBinaryMessage(#message:AnyObject) {
|
private func parseBinaryMessage(#message:String) {
|
||||||
// println(message)
|
// println(message)
|
||||||
if let stringMessage = message as? String {
|
var mutMessage = RegexMutable(message)
|
||||||
var mutMessage = RegexMutable(stringMessage)
|
|
||||||
|
/**
|
||||||
/**
|
Begin check for binary placeholders
|
||||||
Begin check for binary placeholders
|
**/
|
||||||
**/
|
let binaryGroup = mutMessage["^(\\d*)-\\/?(\\w*)?,?(\\d*)?\\[(\".*?\")?,?(.*)?\\]$"].groups()
|
||||||
let binaryGroup = mutMessage["^(\\d*)-\\/?(\\w*)?,?(\\d*)?\\[(\".*?\")?,?(.*)?\\]$"].groups()
|
|
||||||
|
if binaryGroup == nil {
|
||||||
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if binaryGroup[1].hasPrefix("5") {
|
let placeholdersRemoved = mutMessageObject["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"]
|
||||||
// println(binaryGroup)
|
~= "\"~~$2\""
|
||||||
var ackNum:String
|
|
||||||
var event:String
|
var mes:SocketEvent
|
||||||
var mutMessageObject:NSMutableString
|
if ackNum == "" {
|
||||||
var namespace:String?
|
mes = SocketEvent(event: event, args: placeholdersRemoved,
|
||||||
var numberOfPlaceholders:String
|
placeholders: numberOfPlaceholders.toInt()!)
|
||||||
let messageType = RegexMutable(binaryGroup[1])
|
} else {
|
||||||
|
self.currentAck = ackNum.toInt()!
|
||||||
namespace = binaryGroup[2]
|
mes = SocketEvent(event: event, args: placeholdersRemoved,
|
||||||
if binaryGroup[3] != "" {
|
placeholders: numberOfPlaceholders.toInt()!, ackNum: ackNum.toInt())
|
||||||
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
|
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
|
// Handles binary data
|
||||||
internal func parseBinaryData(data:NSData) {
|
internal func parseBinaryData(data:NSData) {
|
||||||
let shouldExecute = self.waitingData[0].addData(data)
|
let shouldExecute = self.waitingData[0].addData(data)
|
||||||
|
|
||||||
if shouldExecute {
|
if shouldExecute {
|
||||||
let socketEvent = self.waitingData.removeAtIndex(0)
|
let socketEvent = self.waitingData.removeAtIndex(0)
|
||||||
var event = socketEvent.event
|
var event = socketEvent.event
|
||||||
var parsedArgs:AnyObject? = SocketIOClient.parseData(socketEvent.args as? String)
|
var parsedArgs:AnyObject? = SocketIOClient.parseData(socketEvent.args as? String)
|
||||||
|
|
||||||
if let args:AnyObject = parsedArgs {
|
if let args:AnyObject = parsedArgs {
|
||||||
let filledInArgs:AnyObject = socketEvent.fillInPlaceholders(args)
|
let filledInArgs:AnyObject = socketEvent.fillInPlaceholders(args)
|
||||||
|
|
||||||
if socketEvent.justAck! {
|
if socketEvent.justAck! {
|
||||||
// Should handle ack
|
// Should handle ack
|
||||||
self.handleAck(socketEvent.ack!, data: filledInArgs)
|
self.handleAck(socketEvent.ack!, data: filledInArgs)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Should do event
|
// Should do event
|
||||||
if socketEvent.ack != nil {
|
if socketEvent.ack != nil {
|
||||||
self.handleEvent(event, data: filledInArgs, isInternalMessage: false,
|
self.handleEvent(event, data: filledInArgs, isInternalMessage: false,
|
||||||
@ -756,13 +755,13 @@ public class SocketIOClient: NSObject {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let filledInArgs:AnyObject = socketEvent.fillInPlaceholders()
|
let filledInArgs:AnyObject = socketEvent.fillInPlaceholders()
|
||||||
|
|
||||||
// Should handle ack
|
// Should handle ack
|
||||||
if socketEvent.justAck! {
|
if socketEvent.justAck! {
|
||||||
self.handleAck(socketEvent.ack!, data: filledInArgs)
|
self.handleAck(socketEvent.ack!, data: filledInArgs)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Should handle ack
|
// Should handle ack
|
||||||
if socketEvent.ack != nil {
|
if socketEvent.ack != nil {
|
||||||
self.handleEvent(event, data: filledInArgs, isInternalMessage: false,
|
self.handleEvent(event, data: filledInArgs, isInternalMessage: false,
|
||||||
@ -773,7 +772,7 @@ public class SocketIOClient: NSObject {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Something happened while polling
|
// Something happened while polling
|
||||||
internal func pollingDidFail(err:NSError?) {
|
internal func pollingDidFail(err:NSError?) {
|
||||||
if !self.reconnecting {
|
if !self.reconnecting {
|
||||||
@ -782,7 +781,7 @@ public class SocketIOClient: NSObject {
|
|||||||
self.tryReconnect()
|
self.tryReconnect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// We lost connection and should attempt to reestablish
|
// We lost connection and should attempt to reestablish
|
||||||
internal func tryReconnect() {
|
internal func tryReconnect() {
|
||||||
if self.reconnectAttempts != -1 && self.currentReconnectAttempt + 1 > self.reconnectAttempts {
|
if self.reconnectAttempts != -1 && self.currentReconnectAttempt + 1 > self.reconnectAttempts {
|
||||||
@ -793,23 +792,23 @@ public class SocketIOClient: NSObject {
|
|||||||
self.reconnecting = false
|
self.reconnecting = false
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.reconnectTimer == nil {
|
if self.reconnectTimer == nil {
|
||||||
self.reconnecting = true
|
self.reconnecting = true
|
||||||
dispatch_async(dispatch_get_main_queue()) {[weak self] in
|
dispatch_async(dispatch_get_main_queue()) {[weak self] in
|
||||||
if self == nil {
|
if self == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
self?.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self!.reconnectWait),
|
self?.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self!.reconnectWait),
|
||||||
target: self!, selector: "tryReconnect", userInfo: nil, repeats: true)
|
target: self!, selector: "tryReconnect", userInfo: nil, repeats: true)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
self.handleEvent("reconnectAttempt", data: self.reconnectAttempts - self.currentReconnectAttempt,
|
self.handleEvent("reconnectAttempt", data: self.reconnectAttempts - self.currentReconnectAttempt,
|
||||||
isInternalMessage: true)
|
isInternalMessage: true)
|
||||||
|
|
||||||
self.currentReconnectAttempt++
|
self.currentReconnectAttempt++
|
||||||
if self.paramConnect {
|
if self.paramConnect {
|
||||||
self.connectWithParams(self.params)
|
self.connectWithParams(self.params)
|
||||||
@ -817,7 +816,7 @@ public class SocketIOClient: NSObject {
|
|||||||
self.connect()
|
self.connect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Called when the socket is closed
|
// Called when the socket is closed
|
||||||
func webSocketDidCloseWithCode(code:Int, reason:String!, wasClean:Bool) {
|
func webSocketDidCloseWithCode(code:Int, reason:String!, wasClean:Bool) {
|
||||||
self.connected = false
|
self.connected = false
|
||||||
@ -829,7 +828,7 @@ public class SocketIOClient: NSObject {
|
|||||||
self.tryReconnect()
|
self.tryReconnect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Called when an error occurs.
|
// Called when an error occurs.
|
||||||
func webSocketDidFailWithError(error:NSError!) {
|
func webSocketDidFailWithError(error:NSError!) {
|
||||||
self.connected = false
|
self.connected = false
|
||||||
@ -842,4 +841,4 @@ public class SocketIOClient: NSObject {
|
|||||||
self.tryReconnect()
|
self.tryReconnect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -16,10 +16,10 @@ import Foundation
|
|||||||
var swiftRegexCache = [String: NSRegularExpression]()
|
var swiftRegexCache = [String: NSRegularExpression]()
|
||||||
|
|
||||||
public class SwiftRegex: NSObject, BooleanType {
|
public class SwiftRegex: NSObject, BooleanType {
|
||||||
|
|
||||||
var target: NSString
|
var target: NSString
|
||||||
var regex: NSRegularExpression
|
var regex: NSRegularExpression
|
||||||
|
|
||||||
init(target:NSString, pattern:String, options:NSRegularExpressionOptions = nil) {
|
init(target:NSString, pattern:String, options:NSRegularExpressionOptions = nil) {
|
||||||
self.target = target
|
self.target = target
|
||||||
if let regex = swiftRegexCache[pattern] {
|
if let regex = swiftRegexCache[pattern] {
|
||||||
@ -37,16 +37,16 @@ public class SwiftRegex: NSObject, BooleanType {
|
|||||||
}
|
}
|
||||||
super.init()
|
super.init()
|
||||||
}
|
}
|
||||||
|
|
||||||
class func failure(message: String) {
|
class func failure(message: String) {
|
||||||
println("SwiftRegex: "+message)
|
println("SwiftRegex: "+message)
|
||||||
//assert(false,"SwiftRegex: failed")
|
//assert(false,"SwiftRegex: failed")
|
||||||
}
|
}
|
||||||
|
|
||||||
final var targetRange: NSRange {
|
final var targetRange: NSRange {
|
||||||
return NSRange(location: 0,length: target.length)
|
return NSRange(location: 0,length: target.length)
|
||||||
}
|
}
|
||||||
|
|
||||||
final func substring(range: NSRange) -> NSString! {
|
final func substring(range: NSRange) -> NSString! {
|
||||||
if ( range.location != NSNotFound ) {
|
if ( range.location != NSNotFound ) {
|
||||||
return target.substringWithRange(range)
|
return target.substringWithRange(range)
|
||||||
@ -54,23 +54,23 @@ public class SwiftRegex: NSObject, BooleanType {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public func doesMatch(options: NSMatchingOptions = nil) -> Bool {
|
public func doesMatch(options: NSMatchingOptions = nil) -> Bool {
|
||||||
return range(options: options).location != NSNotFound
|
return range(options: options).location != NSNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
public func range(options: NSMatchingOptions = nil) -> NSRange {
|
public func range(options: NSMatchingOptions = nil) -> NSRange {
|
||||||
return regex.rangeOfFirstMatchInString(target as String, options: nil, range: targetRange)
|
return regex.rangeOfFirstMatchInString(target as String, options: nil, range: targetRange)
|
||||||
}
|
}
|
||||||
|
|
||||||
public func match(options: NSMatchingOptions = nil) -> String! {
|
public func match(options: NSMatchingOptions = nil) -> String! {
|
||||||
return substring(range(options: options)) as String
|
return substring(range(options: options)) as String
|
||||||
}
|
}
|
||||||
|
|
||||||
public func groups(options: NSMatchingOptions = nil) -> [String]! {
|
public func groups(options: NSMatchingOptions = nil) -> [String]! {
|
||||||
return groupsForMatch( regex.firstMatchInString(target as String, options: options, range: targetRange) )
|
return groupsForMatch( regex.firstMatchInString(target as String, options: options, range: targetRange) )
|
||||||
}
|
}
|
||||||
|
|
||||||
func groupsForMatch(match: NSTextCheckingResult!) -> [String]! {
|
func groupsForMatch(match: NSTextCheckingResult!) -> [String]! {
|
||||||
if match != nil {
|
if match != nil {
|
||||||
var groups = [String]()
|
var groups = [String]()
|
||||||
@ -86,7 +86,7 @@ public class SwiftRegex: NSObject, BooleanType {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public subscript(groupno: Int) -> String! {
|
public subscript(groupno: Int) -> String! {
|
||||||
get {
|
get {
|
||||||
return groups()[groupno]
|
return groups()[groupno]
|
||||||
@ -103,30 +103,30 @@ public class SwiftRegex: NSObject, BooleanType {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func matchResults(options: NSMatchingOptions = nil) -> [NSTextCheckingResult]? {
|
func matchResults(options: NSMatchingOptions = nil) -> [NSTextCheckingResult]? {
|
||||||
let matches = regex.matchesInString(target as String, options: options, range: targetRange)
|
let matches = regex.matchesInString(target as String, options: options, range: targetRange)
|
||||||
as? [NSTextCheckingResult]
|
as? [NSTextCheckingResult]
|
||||||
|
|
||||||
if matches != nil {
|
if matches != nil {
|
||||||
return matches!
|
return matches!
|
||||||
} else {
|
} else {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public func ranges(options: NSMatchingOptions = nil) -> [NSRange] {
|
public func ranges(options: NSMatchingOptions = nil) -> [NSRange] {
|
||||||
return matchResults(options: options)!.map { $0.range }
|
return matchResults(options: options)!.map { $0.range }
|
||||||
}
|
}
|
||||||
|
|
||||||
public func matches(options: NSMatchingOptions = nil) -> [String] {
|
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) as String } )
|
||||||
}
|
}
|
||||||
|
|
||||||
public func allGroups(options: NSMatchingOptions = nil) -> [[String]] {
|
public func allGroups(options: NSMatchingOptions = nil) -> [[String]] {
|
||||||
return matchResults(options: options)!.map { self.groupsForMatch($0) }
|
return matchResults(options: options)!.map { self.groupsForMatch($0) }
|
||||||
}
|
}
|
||||||
|
|
||||||
public func dictionary(options: NSMatchingOptions = nil) -> Dictionary<String,String> {
|
public func dictionary(options: NSMatchingOptions = nil) -> Dictionary<String,String> {
|
||||||
var out = Dictionary<String,String>()
|
var out = Dictionary<String,String>()
|
||||||
for match in matchResults(options: options)! {
|
for match in matchResults(options: options)! {
|
||||||
@ -135,23 +135,23 @@ public class SwiftRegex: NSObject, BooleanType {
|
|||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
func substituteMatches(substitution: (NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String,
|
func substituteMatches(substitution: (NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String,
|
||||||
options:NSMatchingOptions = nil) -> NSMutableString {
|
options:NSMatchingOptions = nil) -> NSMutableString {
|
||||||
let out = NSMutableString()
|
let out = NSMutableString()
|
||||||
var pos = 0
|
var pos = 0
|
||||||
|
|
||||||
regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {
|
regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {
|
||||||
(match: NSTextCheckingResult!, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
|
(match: NSTextCheckingResult!, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
|
||||||
|
|
||||||
let matchRange = match.range
|
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) ) as String )
|
||||||
out.appendString( substitution(match, stop) )
|
out.appendString( substitution(match, stop) )
|
||||||
pos = matchRange.location + matchRange.length
|
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) ) as String )
|
||||||
|
|
||||||
if let mutableTarget = target as? NSMutableString {
|
if let mutableTarget = target as? NSMutableString {
|
||||||
mutableTarget.setString(out as String)
|
mutableTarget.setString(out as String)
|
||||||
return mutableTarget
|
return mutableTarget
|
||||||
@ -164,23 +164,23 @@ public class SwiftRegex: NSObject, BooleanType {
|
|||||||
public func __conversion() -> Bool {
|
public func __conversion() -> Bool {
|
||||||
return doesMatch()
|
return doesMatch()
|
||||||
}
|
}
|
||||||
|
|
||||||
public func __conversion() -> NSRange {
|
public func __conversion() -> NSRange {
|
||||||
return range()
|
return range()
|
||||||
}
|
}
|
||||||
|
|
||||||
public func __conversion() -> String {
|
public func __conversion() -> String {
|
||||||
return match()
|
return match()
|
||||||
}
|
}
|
||||||
|
|
||||||
public func __conversion() -> [String] {
|
public func __conversion() -> [String] {
|
||||||
return matches()
|
return matches()
|
||||||
}
|
}
|
||||||
|
|
||||||
public func __conversion() -> [[String]] {
|
public func __conversion() -> [[String]] {
|
||||||
return allGroups()
|
return allGroups()
|
||||||
}
|
}
|
||||||
|
|
||||||
public func __conversion() -> [String:String] {
|
public func __conversion() -> [String:String] {
|
||||||
return dictionary()
|
return dictionary()
|
||||||
}
|
}
|
||||||
@ -228,11 +228,11 @@ public func ~= (left: SwiftRegex, right: String) -> NSMutableString {
|
|||||||
public func ~= (left: SwiftRegex, right: [String]) -> NSMutableString {
|
public func ~= (left: SwiftRegex, right: [String]) -> NSMutableString {
|
||||||
var matchNumber = 0
|
var matchNumber = 0
|
||||||
return left.substituteMatches({match, stop -> String in
|
return left.substituteMatches({match, stop -> String in
|
||||||
|
|
||||||
if ++matchNumber == right.count {
|
if ++matchNumber == right.count {
|
||||||
stop.memory = true
|
stop.memory = true
|
||||||
}
|
}
|
||||||
|
|
||||||
return left.regex.replacementStringForResult( match,
|
return left.regex.replacementStringForResult( match,
|
||||||
inString: left.target as String, offset: 0, template: right[matchNumber-1] )
|
inString: left.target as String, offset: 0, template: right[matchNumber-1] )
|
||||||
}, options: nil)
|
}, options: nil)
|
||||||
@ -286,11 +286,11 @@ public func & (left: [() -> Void], right: () -> Void) -> [() -> Void] {
|
|||||||
|
|
||||||
public func | (left: [() -> Void], right: () -> Void) {
|
public func | (left: [() -> Void], right: () -> Void) {
|
||||||
let group = dispatch_group_create()
|
let group = dispatch_group_create()
|
||||||
|
|
||||||
for block in left {
|
for block in left {
|
||||||
dispatch_group_async(group, _queue, block)
|
dispatch_group_async(group, _queue, block)
|
||||||
}
|
}
|
||||||
|
|
||||||
dispatch_group_notify(group, dispatch_get_main_queue(), right)
|
dispatch_group_notify(group, dispatch_get_main_queue(), right)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -307,12 +307,12 @@ public func & <R> (left: [() -> R], right: () -> R) -> [() -> R] {
|
|||||||
|
|
||||||
public func | <R> (left: [() -> R], right: (results:[R!]) -> Void) {
|
public func | <R> (left: [() -> R], right: (results:[R!]) -> Void) {
|
||||||
let group = dispatch_group_create()
|
let group = dispatch_group_create()
|
||||||
|
|
||||||
var results = Array<R!>()
|
var results = Array<R!>()
|
||||||
for t in 0..<left.count {
|
for t in 0..<left.count {
|
||||||
results += [nil]
|
results += [nil]
|
||||||
}
|
}
|
||||||
|
|
||||||
for t in 0..<left.count {
|
for t in 0..<left.count {
|
||||||
//dispatch_retain(group)
|
//dispatch_retain(group)
|
||||||
dispatch_group_enter(group)
|
dispatch_group_enter(group)
|
||||||
@ -322,7 +322,7 @@ public func | <R> (left: [() -> R], right: (results:[R!]) -> Void) {
|
|||||||
//dispatch_release(group)
|
//dispatch_release(group)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
dispatch_group_notify(group, dispatch_get_main_queue(), {
|
dispatch_group_notify(group, dispatch_get_main_queue(), {
|
||||||
right(results: results)
|
right(results: results)
|
||||||
})
|
})
|
||||||
|
|||||||
@ -16,7 +16,7 @@ public protocol WebSocketDelegate: class {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public class WebSocket : NSObject, NSStreamDelegate {
|
public class WebSocket : NSObject, NSStreamDelegate {
|
||||||
|
|
||||||
enum OpCode : UInt8 {
|
enum OpCode : UInt8 {
|
||||||
case ContinueFrame = 0x0
|
case ContinueFrame = 0x0
|
||||||
case TextFrame = 0x1
|
case TextFrame = 0x1
|
||||||
@ -27,7 +27,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
case Pong = 0xA
|
case Pong = 0xA
|
||||||
//B-F reserved.
|
//B-F reserved.
|
||||||
}
|
}
|
||||||
|
|
||||||
enum CloseCode : UInt16 {
|
enum CloseCode : UInt16 {
|
||||||
case Normal = 1000
|
case Normal = 1000
|
||||||
case GoingAway = 1001
|
case GoingAway = 1001
|
||||||
@ -40,15 +40,15 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
case PolicyViolated = 1008
|
case PolicyViolated = 1008
|
||||||
case MessageTooBig = 1009
|
case MessageTooBig = 1009
|
||||||
}
|
}
|
||||||
|
|
||||||
enum InternalErrorCode : UInt16 {
|
enum InternalErrorCode : UInt16 {
|
||||||
// 0-999 WebSocket status codes not used
|
// 0-999 WebSocket status codes not used
|
||||||
case OutputStreamWriteError = 1
|
case OutputStreamWriteError = 1
|
||||||
}
|
}
|
||||||
|
|
||||||
//Where the callback is executed. It defaults to the main UI thread queue.
|
//Where the callback is executed. It defaults to the main UI thread queue.
|
||||||
public var queue = dispatch_get_main_queue()
|
public var queue = dispatch_get_main_queue()
|
||||||
|
|
||||||
var optionalProtocols : Array<String>?
|
var optionalProtocols : Array<String>?
|
||||||
//Constant Values.
|
//Constant Values.
|
||||||
let headerWSUpgradeName = "Upgrade"
|
let headerWSUpgradeName = "Upgrade"
|
||||||
@ -69,7 +69,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
let MaskMask: UInt8 = 0x80
|
let MaskMask: UInt8 = 0x80
|
||||||
let PayloadLenMask: UInt8 = 0x7F
|
let PayloadLenMask: UInt8 = 0x7F
|
||||||
let MaxFrameSize: Int = 32
|
let MaxFrameSize: Int = 32
|
||||||
|
|
||||||
class WSResponse {
|
class WSResponse {
|
||||||
var isFin = false
|
var isFin = false
|
||||||
var code: OpCode = .ContinueFrame
|
var code: OpCode = .ContinueFrame
|
||||||
@ -77,7 +77,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
var frameCount = 0
|
var frameCount = 0
|
||||||
var buffer: NSMutableData?
|
var buffer: NSMutableData?
|
||||||
}
|
}
|
||||||
|
|
||||||
public weak var delegate: WebSocketDelegate?
|
public weak var delegate: WebSocketDelegate?
|
||||||
private var url: NSURL
|
private var url: NSURL
|
||||||
private var inputStream: NSInputStream?
|
private var inputStream: NSInputStream?
|
||||||
@ -98,7 +98,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
public var isConnected :Bool {
|
public var isConnected :Bool {
|
||||||
return connected
|
return connected
|
||||||
}
|
}
|
||||||
|
|
||||||
//init the websocket with a url
|
//init the websocket with a url
|
||||||
public init(url: NSURL) {
|
public init(url: NSURL) {
|
||||||
self.url = url
|
self.url = url
|
||||||
@ -130,43 +130,43 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
disconnectedBlock = disconnect
|
disconnectedBlock = disconnect
|
||||||
receivedDataBlock = data
|
receivedDataBlock = data
|
||||||
}
|
}
|
||||||
|
|
||||||
///Connect to the websocket server on a background thread
|
///Connect to the websocket server on a background thread
|
||||||
public func connect() {
|
public func connect() {
|
||||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), {
|
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), {
|
||||||
self.createHTTPRequest()
|
self.createHTTPRequest()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
///disconnect from the websocket server
|
///disconnect from the websocket server
|
||||||
public func disconnect() {
|
public func disconnect() {
|
||||||
writeError(CloseCode.Normal.rawValue)
|
writeError(CloseCode.Normal.rawValue)
|
||||||
}
|
}
|
||||||
|
|
||||||
///write a string to the websocket. This sends it as a text frame.
|
///write a string to the websocket. This sends it as a text frame.
|
||||||
public func writeString(str: String) {
|
public func writeString(str: String) {
|
||||||
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame)
|
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame)
|
||||||
}
|
}
|
||||||
|
|
||||||
///write binary data to the websocket. This sends it as a binary frame.
|
///write binary data to the websocket. This sends it as a binary frame.
|
||||||
public func writeData(data: NSData) {
|
public func writeData(data: NSData) {
|
||||||
dequeueWrite(data, code: .BinaryFrame)
|
dequeueWrite(data, code: .BinaryFrame)
|
||||||
}
|
}
|
||||||
|
|
||||||
//write a ping to the websocket. This sends it as a control frame.
|
//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
|
//yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
|
||||||
public func writePing(data: NSData) {
|
public func writePing(data: NSData) {
|
||||||
dequeueWrite(data, code: .Ping)
|
dequeueWrite(data, code: .Ping)
|
||||||
}
|
}
|
||||||
//private methods below!
|
//private methods below!
|
||||||
|
|
||||||
//private method that starts the connection
|
//private method that starts the connection
|
||||||
private func createHTTPRequest() {
|
private func createHTTPRequest() {
|
||||||
|
|
||||||
let str: NSString = url.absoluteString!
|
let str: NSString = url.absoluteString!
|
||||||
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
|
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
|
||||||
url, kCFHTTPVersion1_1)
|
url, kCFHTTPVersion1_1)
|
||||||
|
|
||||||
var port = url.port
|
var port = url.port
|
||||||
if port == nil {
|
if port == nil {
|
||||||
if url.scheme == "wss" || url.scheme == "https" {
|
if url.scheme == "wss" || url.scheme == "https" {
|
||||||
@ -187,7 +187,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
for (key,value) in headers {
|
for (key,value) in headers {
|
||||||
self.addHeader(urlRequest, key: key, val: value)
|
self.addHeader(urlRequest, key: key, val: value)
|
||||||
}
|
}
|
||||||
|
|
||||||
let serializedRequest: NSData = CFHTTPMessageCopySerializedMessage(urlRequest.takeUnretainedValue()).takeUnretainedValue()
|
let serializedRequest: NSData = CFHTTPMessageCopySerializedMessage(urlRequest.takeUnretainedValue()).takeUnretainedValue()
|
||||||
self.initStreamsWithData(serializedRequest, Int(port!))
|
self.initStreamsWithData(serializedRequest, Int(port!))
|
||||||
}
|
}
|
||||||
@ -215,14 +215,14 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
private func initStreamsWithData(data: NSData, _ port: Int) {
|
private func initStreamsWithData(data: NSData, _ port: Int) {
|
||||||
//higher level API we will cut over to at some point
|
//higher level API we will cut over to at some point
|
||||||
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
|
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
|
||||||
|
|
||||||
var readStream: Unmanaged<CFReadStream>?
|
var readStream: Unmanaged<CFReadStream>?
|
||||||
var writeStream: Unmanaged<CFWriteStream>?
|
var writeStream: Unmanaged<CFWriteStream>?
|
||||||
let h: NSString = url.host!
|
let h: NSString = url.host!
|
||||||
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
|
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
|
||||||
inputStream = readStream!.takeUnretainedValue()
|
inputStream = readStream!.takeUnretainedValue()
|
||||||
outputStream = writeStream!.takeUnretainedValue()
|
outputStream = writeStream!.takeUnretainedValue()
|
||||||
|
|
||||||
inputStream!.delegate = self
|
inputStream!.delegate = self
|
||||||
outputStream!.delegate = self
|
outputStream!.delegate = self
|
||||||
if url.scheme == "wss" || url.scheme == "https" {
|
if url.scheme == "wss" || url.scheme == "https" {
|
||||||
@ -251,7 +251,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
//delegate for the stream methods. Processes incoming bytes
|
//delegate for the stream methods. Processes incoming bytes
|
||||||
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
|
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
|
||||||
|
|
||||||
if eventCode == .HasBytesAvailable {
|
if eventCode == .HasBytesAvailable {
|
||||||
if(aStream == inputStream) {
|
if(aStream == inputStream) {
|
||||||
processInputStream()
|
processInputStream()
|
||||||
@ -282,7 +282,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
self.delegate?.websocketDidDisconnect(self, error: error)
|
self.delegate?.websocketDidDisconnect(self, error: error)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
///handles the incoming bytes and sending them to the proper processing method
|
///handles the incoming bytes and sending them to the proper processing method
|
||||||
private func processInputStream() {
|
private func processInputStream() {
|
||||||
let buf = NSMutableData(capacity: BUFFER_MAX)
|
let buf = NSMutableData(capacity: BUFFER_MAX)
|
||||||
@ -365,7 +365,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
///validates the HTTP is a 101 as per the RFC spec
|
///validates the HTTP is a 101 as per the RFC spec
|
||||||
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
|
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
|
||||||
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, 0)
|
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, 0)
|
||||||
@ -381,7 +381,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
///process the websocket data
|
///process the websocket data
|
||||||
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
||||||
var response = readStack.last
|
var response = readStack.last
|
||||||
@ -563,16 +563,16 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
processResponse(response!)
|
processResponse(response!)
|
||||||
}
|
}
|
||||||
|
|
||||||
let step = offset + Int(len)
|
let step = offset + Int(len)
|
||||||
let extra = bufferLen-step
|
let extra = bufferLen-step
|
||||||
if(extra > 0) {
|
if(extra > 0) {
|
||||||
processExtra((buffer+step), bufferLen: extra)
|
processExtra((buffer+step), bufferLen: extra)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
///process the extra of a buffer
|
///process the extra of a buffer
|
||||||
private func processExtra(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
private func processExtra(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
||||||
if bufferLen < 2 {
|
if bufferLen < 2 {
|
||||||
@ -581,7 +581,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
processRawMessage(buffer, bufferLen: bufferLen)
|
processRawMessage(buffer, bufferLen: bufferLen)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
///process the finished response of a buffer
|
///process the finished response of a buffer
|
||||||
private func processResponse(response: WSResponse) -> Bool {
|
private func processResponse(response: WSResponse) -> Bool {
|
||||||
if response.isFin && response.bytesLeft <= 0 {
|
if response.isFin && response.bytesLeft <= 0 {
|
||||||
@ -615,14 +615,14 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
///Create an error
|
///Create an error
|
||||||
private func errorWithDetail(detail: String, code: UInt16) -> NSError {
|
private func errorWithDetail(detail: String, code: UInt16) -> NSError {
|
||||||
var details = Dictionary<String,String>()
|
var details = Dictionary<String,String>()
|
||||||
details[NSLocalizedDescriptionKey] = detail
|
details[NSLocalizedDescriptionKey] = detail
|
||||||
return NSError(domain: "Websocket", code: Int(code), userInfo: details)
|
return NSError(domain: "Websocket", code: Int(code), userInfo: details)
|
||||||
}
|
}
|
||||||
|
|
||||||
///write a an error to the socket
|
///write a an error to the socket
|
||||||
private func writeError(code: UInt16) {
|
private func writeError(code: UInt16) {
|
||||||
let buf = NSMutableData(capacity: sizeof(UInt16))
|
let buf = NSMutableData(capacity: sizeof(UInt16))
|
||||||
@ -674,7 +674,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
var maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
|
var maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
|
||||||
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
|
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
|
||||||
offset += sizeof(UInt32)
|
offset += sizeof(UInt32)
|
||||||
|
|
||||||
for (var i = 0; i < dataLength; i++) {
|
for (var i = 0; i < dataLength; i++) {
|
||||||
buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)]
|
buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)]
|
||||||
offset += 1
|
offset += 1
|
||||||
@ -706,8 +706,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user