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