Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b7ccb87da | ||
|
|
93f1cfe9dc | ||
|
|
da1cf9eb89 | ||
|
|
57731bebf8 | ||
|
|
81d58fbd69 | ||
|
|
c4731dc298 | ||
|
|
18a561f78a | ||
|
|
85019cca09 | ||
|
|
a4361a04b6 | ||
|
|
ffcd841267 | ||
|
|
98e0c355f9 | ||
|
|
2cae405d29 | ||
|
|
f008f116a6 | ||
|
|
9512c8b9ac | ||
|
|
b0020997c4 | ||
|
|
ce7c9c2c15 | ||
|
|
90f50a1c7e | ||
|
|
182ba0017b | ||
|
|
5b897ddfea | ||
|
|
78aba627a2 | ||
|
|
9044de53d9 | ||
|
|
61ad14f23b | ||
|
|
4c7b3175ca | ||
|
|
5533545adb | ||
|
|
8fa8944672 | ||
|
|
dee508c0f7 | ||
|
|
4de422e7f1 | ||
|
|
4629565aaf | ||
|
|
8b893ad85e | ||
|
|
6985efd7fb | ||
|
|
6ac69d1c2d | ||
|
|
b8b12313fa | ||
|
|
5388084c79 | ||
|
|
48bcada835 | ||
|
|
cf65f56a1d | ||
|
|
18b8f992d9 |
No files matched your search
@@ -47,13 +47,13 @@ Methods
|
||||
-------
|
||||
1. `socket.on(name:String, callback:((data:NSArray?, ack:AckEmitter?) -> Void))` - Adds a handler for an event. Items are passed by an array. `ack` can be used to send an ack when one is requested. See example.
|
||||
2. `socket.onAny(callback:((event:String, items:AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
|
||||
3. `socket.emit(event:String, _ args:AnyObject...)` - Sends a message. Can send multiple args.
|
||||
3. `socket.emit(event:String, _ items:AnyObject...)` - Sends a message. Can send multiple items.
|
||||
4. `socket.emitObjc(event:String, withItems items:[AnyObject])` - `emit` for Objective-C
|
||||
5. `socket.emitWithAck(event:String, _ args:AnyObject...) -> SocketAckHandler` - Sends a message that requests an acknowledgement from the server. Returns a SocketAckHandler which you can use to add an onAck handler. See example.
|
||||
5. `socket.emitWithAck(event:String, _ items:AnyObject...) -> SocketAckHandler` - Sends a message that requests an acknowledgement from the server. Returns a SocketAckHandler which you can use to add an onAck handler. See example.
|
||||
6. `socket.emitWithAckObjc(event:String, withItems items:[AnyObject]) -> SocketAckHandler` - `emitWithAck` for Objective-C.
|
||||
7. `socket.connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
|
||||
8. `socket.connectWithParams(params:[String: AnyObject])` - Establishes a connection to the server passing the specified params. A "connect" event is fired upon successful connection.
|
||||
9. `socket.close()` - Closes the socket. Once a socket is closed it should not be reopened.
|
||||
9. `socket.close(#fast:Bool)` - Closes the socket. Once a socket is closed it should not be reopened. Pass true to fast if you're closing from a background task.
|
||||
|
||||
Events
|
||||
------
|
||||
@@ -72,7 +72,8 @@ let socket = SocketIOClient(socketURL: "https://localhost:8080", opts: [
|
||||
"reconnectAttempts": 5, // Default is -1 (infinite tries)
|
||||
"reconnectWait": 5, // Default is 10
|
||||
"nsp": "swift", // connects to the specified namespace. Default is /
|
||||
"forcePolling": true, // if true, the socket will only use XHR polling, Default is false (polling/WebSockets)
|
||||
"forcePolling": true, // if true the client will only use XHR polling, Default is false (polling/WebSockets)
|
||||
"forceWebsockets": false, // if true the client will only use WebSockets. Trumps forcePolling. Default is false. (polling/WebSockets)
|
||||
"cookies": nil // An array of NSHTTPCookies. Passed during handshake. Default is nil
|
||||
])
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "Socket.IO-Client-Swift"
|
||||
s.version = "1.3.2"
|
||||
s.version = "1.4.4"
|
||||
s.summary = "Socket.IO-client for Swift"
|
||||
s.description = <<-DESC
|
||||
Socket.IO-client for Swift.
|
||||
@@ -12,7 +12,7 @@ Pod::Spec.new do |s|
|
||||
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.3.2' }
|
||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v1.4.4' }
|
||||
s.source_files = "SwiftIO/**/*.swift"
|
||||
s.requires_arc = true
|
||||
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
//
|
||||
// SocketAnyEvent.swift
|
||||
// Socket.IO-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/28/15.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
@objc public class SocketAnyEvent {
|
||||
public let event:String!
|
||||
public var items:[AnyObject]?
|
||||
|
||||
init(event:String, items:[AnyObject]?) {
|
||||
self.event = event
|
||||
self.items = items
|
||||
}
|
||||
}
|
||||
+153
-126
@@ -30,7 +30,7 @@ extension String {
|
||||
}
|
||||
}
|
||||
|
||||
private typealias Probe = (msg:String, type:PacketType, data:[NSData]?)
|
||||
private typealias Probe = (msg:String, type:PacketType, data:ContiguousArray<NSData>?)
|
||||
private typealias ProbeWaitQueue = [Probe]
|
||||
|
||||
public enum PacketType: String {
|
||||
@@ -47,15 +47,17 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
unowned let client:SocketEngineClient
|
||||
private let workQueue = NSOperationQueue()
|
||||
private let emitQueue = dispatch_queue_create(
|
||||
"emitQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||
"engineEmitQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||
private let parseQueue = dispatch_queue_create(
|
||||
"parseQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||
"engineParseQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||
private let handleQueue = dispatch_queue_create(
|
||||
"handleQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||
"engineHandleQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||
private let session:NSURLSession!
|
||||
private var closed = false
|
||||
private var _connected = false
|
||||
private var fastUpgrade = false
|
||||
private var forcePolling = false
|
||||
private var forceWebsockets = false
|
||||
private var pingTimer:NSTimer?
|
||||
private var postWait = [String]()
|
||||
private var _polling = true
|
||||
@@ -81,17 +83,30 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
var ws:WebSocket?
|
||||
|
||||
init(client:SocketEngineClient, forcePolling:Bool, withCookies cookies:[NSHTTPCookie]?) {
|
||||
self.client = client
|
||||
self.forcePolling = forcePolling
|
||||
self.cookies = cookies
|
||||
self.session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
|
||||
delegate: nil, delegateQueue: self.workQueue)
|
||||
public init(client:SocketEngineClient, forcePolling:Bool,
|
||||
forceWebsockets:Bool, withCookies cookies:[NSHTTPCookie]?) {
|
||||
self.client = client
|
||||
self.forcePolling = forcePolling
|
||||
self.forceWebsockets = forceWebsockets
|
||||
self.cookies = cookies
|
||||
self.session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
|
||||
delegate: nil, delegateQueue: self.workQueue)
|
||||
}
|
||||
|
||||
func close() {
|
||||
public func close(#fast:Bool) {
|
||||
self.pingTimer?.invalidate()
|
||||
self.send(PacketType.CLOSE.rawValue)
|
||||
self.closed = true
|
||||
|
||||
if self.polling {
|
||||
self.write("", withType: PacketType.CLOSE, withData: nil)
|
||||
self.client.didForceClose("Disconnect")
|
||||
} else {
|
||||
self.ws?.disconnect()
|
||||
|
||||
if fast {
|
||||
self.client.didForceClose("Fast Disconnect")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func createBinaryDataForSend(data:NSData) -> (NSData?, String?) {
|
||||
@@ -145,6 +160,16 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
return (urlPolling, urlWebSocket)
|
||||
}
|
||||
|
||||
private func createWebsocket(andConnect connect:Bool) {
|
||||
self.ws = WebSocket(url: NSURL(string: self.urlWebSocket! + "&sid=\(self.sid)")!)
|
||||
self.ws?.queue = self.handleQueue
|
||||
self.ws?.delegate = self
|
||||
|
||||
if connect {
|
||||
self.ws?.connect()
|
||||
}
|
||||
}
|
||||
|
||||
private func doFastUpgrade() {
|
||||
self.sendWebSocketMessage("", withType: PacketType.UPGRADE)
|
||||
self._websocket = true
|
||||
@@ -159,31 +184,37 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
|
||||
self.waitingForPoll = true
|
||||
self.doRequest(self.parsePollingMessage)
|
||||
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)&b64=1")!)
|
||||
|
||||
self.doRequest(req)
|
||||
}
|
||||
|
||||
private func doRequest(callback:(String) -> Void) {
|
||||
private func doRequest(req:NSMutableURLRequest) {
|
||||
if !self.polling {
|
||||
return
|
||||
}
|
||||
|
||||
let req = NSURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
|
||||
req.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
|
||||
|
||||
// NSLog("Doing request: \(req)")
|
||||
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
||||
if self == nil {
|
||||
return
|
||||
} else if err != nil {
|
||||
if self!.polling {
|
||||
self?.handlePollingFailed(err)
|
||||
self?.handlePollingFailed(err.localizedDescription)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// println(data)
|
||||
// NSLog("Got response: \(res)")
|
||||
|
||||
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
|
||||
dispatch_async(self!.parseQueue) {callback(str)}
|
||||
dispatch_async(self!.parseQueue) {
|
||||
self?.parsePollingMessage(str)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
self?.waitingForPoll = false
|
||||
@@ -191,7 +222,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
if self!.fastUpgrade {
|
||||
self?.doFastUpgrade()
|
||||
return
|
||||
} else {
|
||||
} else if !self!.closed && !self!.websocket {
|
||||
self?.doPoll()
|
||||
}
|
||||
}.resume()
|
||||
@@ -247,7 +278,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
if self == nil {
|
||||
return
|
||||
} else if err != nil && self!.polling {
|
||||
self?.handlePollingFailed(err)
|
||||
self?.handlePollingFailed(err.localizedDescription)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -270,27 +301,37 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
|
||||
// A poll failed, tell the client about it
|
||||
private func handlePollingFailed(reason:NSError?) {
|
||||
assert(self.polling, "Polling failed when we're not polling")
|
||||
private func handlePollingFailed(reason:String) {
|
||||
self._connected = false
|
||||
self.ws?.disconnect()
|
||||
self.pingTimer?.invalidate()
|
||||
self.waitingForPoll = false
|
||||
self.waitingForPost = false
|
||||
|
||||
if !self.client.reconnecting {
|
||||
self._connected = false
|
||||
self.ws?.disconnect()
|
||||
self.pingTimer?.invalidate()
|
||||
self.waitingForPoll = false
|
||||
self.waitingForPost = false
|
||||
if !self.closed && !self.client.reconnecting {
|
||||
self.client.pollingDidFail(reason)
|
||||
} else if !self.client.reconnecting {
|
||||
self.client.didForceClose(reason)
|
||||
}
|
||||
}
|
||||
|
||||
func open(opts:[String: AnyObject]? = nil) {
|
||||
public func open(opts:[String: AnyObject]? = nil) {
|
||||
if self.connected {
|
||||
assert(false, "We're in a bad state, this shouldn't happen.")
|
||||
fatalError("Engine tried to open while connected")
|
||||
}
|
||||
|
||||
self.closed = false
|
||||
let (urlPolling, urlWebSocket) = self.createURLs(opts)
|
||||
self.urlPolling = urlPolling
|
||||
self.urlWebSocket = urlWebSocket
|
||||
|
||||
if self.forceWebsockets {
|
||||
self._polling = false
|
||||
self._websocket = true
|
||||
self.createWebsocket(andConnect: true)
|
||||
return
|
||||
}
|
||||
|
||||
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
|
||||
|
||||
if self.cookies != nil {
|
||||
@@ -298,58 +339,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
reqPolling.allHTTPHeaderFields = headers
|
||||
}
|
||||
|
||||
|
||||
self.session.dataTaskWithRequest(reqPolling) {[weak self] data, res, err in
|
||||
var err2:NSError?
|
||||
if self == nil {
|
||||
return
|
||||
} else if err != nil || data == nil {
|
||||
self?.handlePollingFailed(err)
|
||||
return
|
||||
}
|
||||
|
||||
if let dataString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
|
||||
let parsed:[String]? = dataString["(\\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
|
||||
}
|
||||
|
||||
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
|
||||
self?.ws?.delegate = self
|
||||
self?.ws?.connect()
|
||||
}
|
||||
} else {
|
||||
NSLog("Error handshaking")
|
||||
return
|
||||
}
|
||||
|
||||
if let pingInterval = json["pingInterval"] as? Int {
|
||||
self?.pingInterval = pingInterval / 1000
|
||||
}
|
||||
}
|
||||
|
||||
self?.doPoll()
|
||||
self?.startPingTimer()
|
||||
}}.resume()
|
||||
self.doRequest(reqPolling)
|
||||
}
|
||||
|
||||
// Translatation of engine.io-parser#decodePayload
|
||||
@@ -382,7 +372,8 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
length += chr
|
||||
} else {
|
||||
if length == "" || testLength(length, &n) {
|
||||
println("failure in parsePollingMessage")
|
||||
NSLog("parsing error: \(str)")
|
||||
self.handlePollingFailed("Error parsing XHR message")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -390,7 +381,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
|
||||
if let lengthInt = length.toInt() {
|
||||
if lengthInt != msg.length {
|
||||
println("parsing error")
|
||||
NSLog("parsing error: \(str)")
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -398,7 +389,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
if msg.length != 0 {
|
||||
// Be sure to capture the value of the msg
|
||||
dispatch_async(self.handleQueue) {[weak self, msg] in
|
||||
self?.parseEngineMessage(msg)
|
||||
self?.parseEngineMessage(msg, fromPolling: true)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -416,18 +407,12 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
private func parseEngineMessage(var message:String) {
|
||||
private func parseEngineMessage(var message:String, fromPolling:Bool) {
|
||||
// NSLog("Engine got message: \(message)")
|
||||
if self.polling {
|
||||
if fromPolling {
|
||||
fixDoubleUTF8(&message)
|
||||
}
|
||||
|
||||
// We should upgrade
|
||||
if message == "3probe" {
|
||||
self.upgradeTransport()
|
||||
return
|
||||
}
|
||||
|
||||
let type = message["^(\\d)"].groups()?[1]
|
||||
|
||||
if type != PacketType.MESSAGE.rawValue {
|
||||
@@ -452,11 +437,50 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
self.doPoll()
|
||||
return
|
||||
} else if type == PacketType.PONG.rawValue {
|
||||
// We should upgrade
|
||||
if message == "3probe" {
|
||||
self.upgradeTransport()
|
||||
return
|
||||
}
|
||||
} else if type == PacketType.OPEN.rawValue {
|
||||
var err:NSError?
|
||||
|
||||
message.removeAtIndex(message.startIndex)
|
||||
let mesData = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
|
||||
|
||||
if let json = NSJSONSerialization.JSONObjectWithData(mesData,
|
||||
options: NSJSONReadingOptions.AllowFragments, error: &err) as? NSDictionary {
|
||||
if let sid = json["sid"] as? String {
|
||||
// println(json)
|
||||
self.sid = sid
|
||||
self._connected = true
|
||||
if !self.forcePolling && !self.forceWebsockets {
|
||||
self.createWebsocket(andConnect: true)
|
||||
}
|
||||
} else {
|
||||
NSLog("Error handshaking")
|
||||
return
|
||||
}
|
||||
|
||||
if let pingInterval = json["pingInterval"] as? Int {
|
||||
self.pingInterval = pingInterval / 1000
|
||||
}
|
||||
} else {
|
||||
fatalError("Error parsing engine connect")
|
||||
}
|
||||
|
||||
self.startPingTimer()
|
||||
|
||||
if !self.forceWebsockets {
|
||||
self.doPoll()
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if message == PacketType.CLOSE.rawValue {
|
||||
// do nothing
|
||||
} else if type == PacketType.CLOSE.rawValue {
|
||||
if self.polling {
|
||||
self.client.didForceClose("Disconnect")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
// println("Got something idk what to do with")
|
||||
@@ -478,10 +502,8 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Send a message with type 4
|
||||
*/
|
||||
public func send(msg:String, datas:[NSData]? = nil) {
|
||||
/// Send an engine message (4)
|
||||
public func send(msg:String, withData datas:ContiguousArray<NSData>?) {
|
||||
if self.probing {
|
||||
self.probeWait.append((msg, PacketType.MESSAGE, datas))
|
||||
} else {
|
||||
@@ -498,9 +520,8 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
|
||||
private func sendPollMessage(var msg:String, withType type:PacketType,
|
||||
datas:[NSData]? = nil) {
|
||||
datas:ContiguousArray<NSData>? = nil) {
|
||||
// println("Sending poll: \(msg) as type: \(type.rawValue)")
|
||||
|
||||
doubleEncodeUTF8(&msg)
|
||||
let strMsg = "\(type.rawValue)\(msg)"
|
||||
|
||||
@@ -519,18 +540,19 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
private func sendWebSocketMessage(str:String, withType type:PacketType, datas:[NSData]? = nil) {
|
||||
// println("Sending ws: \(str) as type: \(type.rawValue)")
|
||||
self.ws?.writeString("\(type.rawValue)\(str)")
|
||||
|
||||
if datas != nil {
|
||||
for data in datas! {
|
||||
let (data, nilString) = self.createBinaryDataForSend(data)
|
||||
if data != nil {
|
||||
self.ws?.writeData(data!)
|
||||
private func sendWebSocketMessage(str:String, withType type:PacketType,
|
||||
datas:ContiguousArray<NSData>? = nil) {
|
||||
// println("Sending ws: \(str) as type: \(type.rawValue)")
|
||||
self.ws?.writeString("\(type.rawValue)\(str)")
|
||||
|
||||
if datas != nil {
|
||||
for data in datas! {
|
||||
let (data, nilString) = self.createBinaryDataForSend(data)
|
||||
if data != nil {
|
||||
self.ws?.writeData(data!)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Starts the ping timer
|
||||
@@ -556,21 +578,17 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
public func write(msg:String, withType type:PacketType, withData data:[NSData]?) {
|
||||
public func write(msg:String, withType type:PacketType, withData data:ContiguousArray<NSData>?) {
|
||||
dispatch_async(self.emitQueue) {[weak self] in
|
||||
if self == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if !self!.connected {
|
||||
if self == nil || !self!.connected {
|
||||
return
|
||||
}
|
||||
|
||||
if self!.websocket {
|
||||
// NSLog("writing ws: \(msg):\(datas)")
|
||||
// NSLog("writing ws: \(msg):\(data)")
|
||||
self?.sendWebSocketMessage(msg, withType: type, datas: data)
|
||||
} else {
|
||||
// NSLog("writing poll: \(msg):\(datas)")
|
||||
// NSLog("writing poll: \(msg):\(data)")
|
||||
self?.sendPollMessage(msg, withType: type, datas: data)
|
||||
}
|
||||
}
|
||||
@@ -580,8 +598,15 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
|
||||
public func websocketDidConnect(socket:WebSocket) {
|
||||
self.websocketConnected = true
|
||||
self.probing = true
|
||||
self.probeWebSocket()
|
||||
|
||||
if !self.forceWebsockets {
|
||||
self.probing = true
|
||||
self.probeWebSocket()
|
||||
} else {
|
||||
self._connected = true
|
||||
self.probing = false
|
||||
self._polling = false
|
||||
}
|
||||
}
|
||||
|
||||
public func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
|
||||
@@ -592,15 +617,17 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
self.pingTimer?.invalidate()
|
||||
self._connected = false
|
||||
self._websocket = false
|
||||
self._polling = true
|
||||
self.client.webSocketDidCloseWithCode(1, reason: "Socket Disconnect", wasClean: true)
|
||||
|
||||
let reason = error?.localizedDescription
|
||||
self.client.webSocketDidCloseWithCode(1,
|
||||
reason: reason == nil ? "Socket Disconnected" : reason!)
|
||||
} else {
|
||||
self.flushProbeWait()
|
||||
}
|
||||
}
|
||||
|
||||
public func websocketDidReceiveMessage(socket:WebSocket, text:String) {
|
||||
self.parseEngineMessage(text)
|
||||
self.parseEngineMessage(text, fromPolling: false)
|
||||
}
|
||||
|
||||
public func websocketDidReceiveData(socket:WebSocket, data:NSData) {
|
||||
|
||||
@@ -26,16 +26,16 @@
|
||||
import Foundation
|
||||
|
||||
@objc public protocol SocketEngineClient {
|
||||
var ackQueue:dispatch_queue_attr_t! {get}
|
||||
var handleQueue:dispatch_queue_attr_t! {get}
|
||||
var emitQueue:dispatch_queue_attr_t! {get}
|
||||
var reconnecting:Bool {get}
|
||||
var socketURL:String {get}
|
||||
var secure:Bool {get}
|
||||
|
||||
func didForceClose(reason:String)
|
||||
func parseSocketMessage(msg:String)
|
||||
func parseBinaryData(data:NSData)
|
||||
func pollingDidFail(err:NSError?)
|
||||
func webSocketDidCloseWithCode(code:Int, reason:String, wasClean:Bool)
|
||||
func pollingDidFail(err:String)
|
||||
func webSocketDidCloseWithCode(code:Int, reason:String)
|
||||
func webSocketDidFailWithError(error:NSError)
|
||||
}
|
||||
@@ -1,250 +0,0 @@
|
||||
//
|
||||
// Event.swift
|
||||
// Socket.IO-Swift
|
||||
//
|
||||
// Created by Erik Little on 1/18/15.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
class SocketEvent {
|
||||
let justAck:Bool!
|
||||
var ack:Int?
|
||||
var args:AnyObject!
|
||||
lazy var currentPlace = 0
|
||||
lazy var datas = [NSData]()
|
||||
var event:String!
|
||||
var placeholders:Int!
|
||||
|
||||
init(event:String, args:AnyObject?, placeholders:Int = 0, ackNum:Int? = nil, justAck:Bool = false) {
|
||||
self.event = event
|
||||
self.args = args
|
||||
self.placeholders = placeholders
|
||||
self.ack = ackNum
|
||||
self.justAck = justAck
|
||||
}
|
||||
|
||||
func addData(data:NSData) -> Bool {
|
||||
func checkDoEvent() -> Bool {
|
||||
if self.placeholders == self.currentPlace {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if checkDoEvent() {
|
||||
return true
|
||||
}
|
||||
|
||||
self.datas.append(data)
|
||||
self.currentPlace++
|
||||
|
||||
if checkDoEvent() {
|
||||
self.currentPlace = 0
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
class func createMessageForEvent(event:String, withArgs args:[AnyObject],
|
||||
hasBinary:Bool, withDatas datas:Int = 0, toNamespace nsp:String?, wantsAck ack:Int? = nil) -> String {
|
||||
|
||||
var message:String
|
||||
var jsonSendError:NSError?
|
||||
|
||||
if !hasBinary {
|
||||
if nsp == nil {
|
||||
if ack == nil {
|
||||
message = "2[\"\(event)\""
|
||||
} else {
|
||||
message = "2\(ack!)[\"\(event)\""
|
||||
}
|
||||
} else {
|
||||
if ack == nil {
|
||||
message = "2/\(nsp!),[\"\(event)\""
|
||||
} else {
|
||||
message = "2/\(nsp!),\(ack!)[\"\(event)\""
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if nsp == nil {
|
||||
if ack == nil {
|
||||
message = "5\(datas)-[\"\(event)\""
|
||||
} else {
|
||||
message = "5\(datas)-\(ack!)[\"\(event)\""
|
||||
}
|
||||
} else {
|
||||
if ack == nil {
|
||||
message = "5\(datas)-/\(nsp!),[\"\(event)\""
|
||||
} else {
|
||||
message = "5\(datas)-/\(nsp!),\(ack!)[\"\(event)\""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return self.completeMessage(message, args: args)
|
||||
}
|
||||
|
||||
class func createAck(ack:Int, withArgs args:[AnyObject], withAckType ackType:Int,
|
||||
withNsp nsp:String, withBinary binary:Int = 0) -> String {
|
||||
var msg:String
|
||||
|
||||
if ackType == 3 {
|
||||
if nsp == "/" {
|
||||
msg = "3\(ack)["
|
||||
} else {
|
||||
msg = "3/\(nsp),\(ack)["
|
||||
}
|
||||
} else {
|
||||
if nsp == "/" {
|
||||
msg = "6\(binary)-\(ack)["
|
||||
} else {
|
||||
msg = "6\(binary)-/\(nsp),\(ack)["
|
||||
}
|
||||
}
|
||||
|
||||
return self.completeMessage(msg, args: args, ack: true)
|
||||
}
|
||||
|
||||
private class func completeMessage(var message:String, args:[AnyObject], ack:Bool = false) -> String {
|
||||
var err:NSError?
|
||||
|
||||
if args.count == 0 {
|
||||
return message + "]"
|
||||
} else if !ack {
|
||||
message += ","
|
||||
}
|
||||
|
||||
for arg in args {
|
||||
|
||||
if arg is NSDictionary || arg is [AnyObject] {
|
||||
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
|
||||
options: NSJSONWritingOptions(0), error: &err)
|
||||
let jsonString = NSString(data: jsonSend!, encoding: NSUTF8StringEncoding)
|
||||
|
||||
message += jsonString! as String
|
||||
message += ","
|
||||
continue
|
||||
}
|
||||
|
||||
if arg is String {
|
||||
message += "\"\(arg)\""
|
||||
message += ","
|
||||
continue
|
||||
}
|
||||
|
||||
message += "\(arg)"
|
||||
message += ","
|
||||
}
|
||||
|
||||
if message != "" {
|
||||
message.removeAtIndex(message.endIndex.predecessor())
|
||||
}
|
||||
|
||||
return message + "]"
|
||||
}
|
||||
|
||||
private func fillInArray(arr:NSArray) -> NSArray {
|
||||
var newArr = [AnyObject](count: arr.count, repeatedValue: 0)
|
||||
// println(arr)
|
||||
|
||||
for i in 0..<arr.count {
|
||||
if let nest = arr[i] as? NSArray {
|
||||
newArr[i] = self.fillInArray(nest)
|
||||
} else if let dict = arr[i] as? NSDictionary {
|
||||
newArr[i] = self.fillInDict(dict)
|
||||
} else if let str = arr[i] as? String {
|
||||
if let num = str["~~(\\d)"].groups() {
|
||||
newArr[i] = self.datas[num[1].toInt()!]
|
||||
} else {
|
||||
newArr[i] = arr[i]
|
||||
}
|
||||
} else {
|
||||
newArr[i] = arr[i]
|
||||
}
|
||||
}
|
||||
|
||||
return newArr
|
||||
}
|
||||
|
||||
private func fillInDict(dict:NSDictionary) -> NSDictionary {
|
||||
var newDict = [String: AnyObject]()
|
||||
|
||||
for (key, value) in dict {
|
||||
newDict[key as String] = value
|
||||
|
||||
// If the value is a string we need to check
|
||||
// if it is a placeholder for data
|
||||
if let str = value as? String {
|
||||
if let num = str["~~(\\d)"].groups() {
|
||||
newDict[key as String] = self.datas[num[1].toInt()!]
|
||||
} else {
|
||||
newDict[key as String] = str
|
||||
}
|
||||
} else if let nestDict = value as? NSDictionary {
|
||||
newDict[key as String] = self.fillInDict(nestDict)
|
||||
} else if let arr = value as? NSArray {
|
||||
newDict[key as String] = self.fillInArray(arr)
|
||||
}
|
||||
}
|
||||
|
||||
return newDict
|
||||
}
|
||||
|
||||
func fillInPlaceholders(_ args:AnyObject = true) -> AnyObject {
|
||||
if let dict = args as? NSDictionary {
|
||||
return self.fillInDict(dict)
|
||||
} else if let arr = args as? NSArray {
|
||||
return self.fillInArray(args as NSArray)
|
||||
} else if let string = args as? String {
|
||||
if string == "~~\(self.currentPlace)" {
|
||||
return self.datas[0]
|
||||
}
|
||||
} else if args is Bool {
|
||||
// We have multiple items
|
||||
// Do it live
|
||||
let argsAsArray = "[\(self.args)]"
|
||||
if let parsedArr = SocketParser.parseData(argsAsArray) as? NSArray {
|
||||
var returnArr = [AnyObject](count: parsedArr.count, repeatedValue: 0)
|
||||
|
||||
for i in 0..<parsedArr.count {
|
||||
if let str = parsedArr[i] as? String {
|
||||
if let num = str["~~(\\d)"].groups() {
|
||||
returnArr[i] = self.datas[num[1].toInt()!]
|
||||
} else {
|
||||
returnArr[i] = str
|
||||
}
|
||||
} else if let arr = parsedArr[i] as? NSArray {
|
||||
returnArr[i] = self.fillInArray(arr)
|
||||
} else if let dict = parsedArr[i] as? NSDictionary {
|
||||
returnArr[i] = self.fillInDict(dict)
|
||||
} else {
|
||||
returnArr[i] = parsedArr[i]
|
||||
}
|
||||
}
|
||||
return returnArr
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -25,13 +25,12 @@
|
||||
import Foundation
|
||||
|
||||
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
|
||||
public typealias AnyHandler = (event:String, items:AnyObject?)
|
||||
public typealias AckEmitter = (AnyObject...) -> Void
|
||||
|
||||
private func emitAckCallback(socket:SocketIOClient, num:Int, type:Int)
|
||||
private func emitAckCallback(socket:SocketIOClient, num:Int)
|
||||
// Curried
|
||||
(items:AnyObject...) -> Void {
|
||||
socket.emitAck(num, withData: items, withAckType: type)
|
||||
socket.emitAck(num, withData: items)
|
||||
}
|
||||
|
||||
class SocketEventHandler {
|
||||
@@ -46,7 +45,7 @@ class SocketEventHandler {
|
||||
func executeCallback(_ items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
|
||||
withSocket socket:SocketIOClient? = nil) {
|
||||
dispatch_async(dispatch_get_main_queue()) {[weak self] in
|
||||
self?.callback?(items, ack != nil ? emitAckCallback(socket!, ack!, type!) : nil)
|
||||
self?.callback?(items, ack != nil ? emitAckCallback(socket!, ack!) : nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
+117
-112
@@ -27,26 +27,25 @@ import Foundation
|
||||
public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
let reconnectAttempts:Int!
|
||||
private lazy var params = [String: AnyObject]()
|
||||
private var ackHandlers = [SocketAckHandler]()
|
||||
private var anyHandler:((AnyHandler) -> Void)?
|
||||
private var ackHandlers = ContiguousArray<SocketAckHandler>()
|
||||
private var anyHandler:((SocketAnyEvent) -> Void)?
|
||||
private var _closed = false
|
||||
private var _connected = false
|
||||
private var _connecting = false
|
||||
private var currentReconnectAttempt = 0
|
||||
private var forcePolling = false
|
||||
private var handlers = [SocketEventHandler]()
|
||||
private var forceWebsockets = false
|
||||
private var handlers = ContiguousArray<SocketEventHandler>()
|
||||
private var paramConnect = false
|
||||
private var _secure = false
|
||||
private var _sid:String?
|
||||
private var _reconnecting = false
|
||||
private var reconnectTimer:NSTimer?
|
||||
|
||||
internal var currentAck = -1
|
||||
internal var waitingData = [SocketEvent]()
|
||||
var currentAck = -1
|
||||
var waitingData = ContiguousArray<SocketPacket>()
|
||||
|
||||
public let socketURL:String
|
||||
public let ackQueue = dispatch_queue_create("ackQueue".cStringUsingEncoding(NSUTF8StringEncoding),
|
||||
DISPATCH_QUEUE_SERIAL)
|
||||
public let handleQueue = dispatch_queue_create("handleQueue".cStringUsingEncoding(NSUTF8StringEncoding),
|
||||
DISPATCH_QUEUE_SERIAL)
|
||||
public let emitQueue = dispatch_queue_create("emitQueue".cStringUsingEncoding(NSUTF8StringEncoding),
|
||||
@@ -62,7 +61,7 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
}
|
||||
public var cookies:[NSHTTPCookie]?
|
||||
public var engine:SocketEngine?
|
||||
public var nsp:String?
|
||||
public var nsp = "/"
|
||||
public var reconnects = true
|
||||
public var reconnecting:Bool {
|
||||
return self._reconnecting
|
||||
@@ -104,7 +103,11 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
self.reconnectWait = abs(reconnectWait)
|
||||
}
|
||||
|
||||
if let nsp = opts!["nsp"] as? String {
|
||||
if var nsp = opts!["nsp"] as? String {
|
||||
if nsp != "/" && nsp.hasPrefix("/") {
|
||||
nsp.removeAtIndex(nsp.startIndex)
|
||||
}
|
||||
|
||||
self.nsp = nsp
|
||||
}
|
||||
|
||||
@@ -112,6 +115,10 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
self.forcePolling = polling
|
||||
}
|
||||
|
||||
if let ws = opts!["forceWebsockets"] as? Bool {
|
||||
self.forceWebsockets = ws
|
||||
}
|
||||
|
||||
if let cookies = opts!["cookies"] as? [NSHTTPCookie] {
|
||||
self.cookies = cookies
|
||||
}
|
||||
@@ -120,25 +127,30 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
}
|
||||
|
||||
super.init()
|
||||
|
||||
self.engine = SocketEngine(client: self,
|
||||
forcePolling: self.forcePolling,
|
||||
withCookies: self.cookies)
|
||||
}
|
||||
|
||||
public convenience init(socketURL:String, options:NSDictionary?) {
|
||||
self.init(socketURL: socketURL, opts: options)
|
||||
}
|
||||
|
||||
private func addEngine() {
|
||||
self.engine = SocketEngine(client: self,
|
||||
forcePolling: self.forcePolling,
|
||||
forceWebsockets: self.forceWebsockets,
|
||||
withCookies: self.cookies)
|
||||
}
|
||||
|
||||
/**
|
||||
Closes the socket. Only reopen the same socket if you know what you're doing.
|
||||
Will turn off automatic reconnects.
|
||||
Pass true to fast if you're closing from a background task
|
||||
*/
|
||||
public func close() {
|
||||
self._closed = true
|
||||
public func close(#fast:Bool) {
|
||||
self.reconnects = false
|
||||
self._connecting = false
|
||||
self._connected = false
|
||||
self._reconnecting = false
|
||||
self.engine?.close()
|
||||
self.engine?.close(fast: fast)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -150,6 +162,11 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
self._closed = false
|
||||
}
|
||||
|
||||
if self.connected {
|
||||
return
|
||||
}
|
||||
|
||||
self.addEngine()
|
||||
self.engine?.open()
|
||||
}
|
||||
|
||||
@@ -162,9 +179,14 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
self._closed = false
|
||||
}
|
||||
|
||||
if self.connected {
|
||||
return
|
||||
}
|
||||
|
||||
self.params = params
|
||||
self.paramConnect = true
|
||||
|
||||
self.addEngine()
|
||||
self.engine?.open(opts: params)
|
||||
}
|
||||
|
||||
@@ -184,25 +206,29 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
}
|
||||
|
||||
/// Server wants us to die
|
||||
func didForceClose(#message:String) {
|
||||
public func didForceClose(reason:String) {
|
||||
if self.closed {
|
||||
return
|
||||
}
|
||||
|
||||
self._closed = true
|
||||
self._connected = false
|
||||
self.reconnects = false
|
||||
self._connecting = false
|
||||
self._reconnecting = false
|
||||
self.handleEvent("disconnect", data: message, isInternalMessage: true)
|
||||
self.handleEvent("disconnect", data: [reason], isInternalMessage: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Send a message to the server
|
||||
*/
|
||||
public func emit(event:String, _ args:AnyObject...) {
|
||||
public func emit(event:String, _ items:AnyObject...) {
|
||||
if !self.connected {
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(self.emitQueue) {[weak self] in
|
||||
self?._emit(event, args)
|
||||
self?._emit(event, items)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -211,14 +237,21 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
Same as emit, but meant for Objective-C
|
||||
*/
|
||||
public func emitObjc(event:String, withItems items:[AnyObject]) {
|
||||
self.emit(event, items)
|
||||
if !self.connected {
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(self.emitQueue) {[weak self] in
|
||||
self?._emit(event, items)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
|
||||
an ack.
|
||||
*/
|
||||
public func emitWithAck(event:String, _ args:AnyObject...) -> SocketAckHandler {
|
||||
public func emitWithAck(event:String, _ items:AnyObject...) -> SocketAckHandler {
|
||||
if !self.connected {
|
||||
return SocketAckHandler(event: "fail", socket: self)
|
||||
}
|
||||
@@ -229,7 +262,7 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
self.ackHandlers.append(ackHandler)
|
||||
|
||||
dispatch_async(self.emitQueue) {[weak self, ack = self.currentAck] in
|
||||
self?._emit(event, args, ack: ack)
|
||||
self?._emit(event, items, ack: ack)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -240,73 +273,58 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
Same as emitWithAck, but for Objective-C
|
||||
*/
|
||||
public func emitWithAckObjc(event:String, withItems items:[AnyObject]) -> SocketAckHandler {
|
||||
return self.emitWithAck(event, items)
|
||||
if !self.connected {
|
||||
return SocketAckHandler(event: "fail", socket: self)
|
||||
}
|
||||
|
||||
self.currentAck++
|
||||
let ackHandler = SocketAckHandler(event: event,
|
||||
ackNum: self.currentAck, socket: self)
|
||||
self.ackHandlers.append(ackHandler)
|
||||
|
||||
dispatch_async(self.emitQueue) {[weak self, ack = self.currentAck] in
|
||||
self?._emit(event, items, ack: ack)
|
||||
return
|
||||
}
|
||||
|
||||
return ackHandler
|
||||
}
|
||||
|
||||
private func _emit(event:String, _ args:[AnyObject], ack:Int? = nil) {
|
||||
var frame:SocketEvent
|
||||
var str:String
|
||||
|
||||
let (items, hasBinary, emitDatas) = SocketParser.parseEmitArgs(args)
|
||||
|
||||
if !self.connected {
|
||||
return
|
||||
}
|
||||
|
||||
if hasBinary {
|
||||
if ack == nil {
|
||||
str = SocketEvent.createMessageForEvent(event, withArgs: items,
|
||||
hasBinary: true, withDatas: emitDatas.count, toNamespace: self.nsp)
|
||||
} else {
|
||||
str = SocketEvent.createMessageForEvent(event, withArgs: items,
|
||||
hasBinary: true, withDatas: emitDatas.count, toNamespace: self.nsp, wantsAck: ack)
|
||||
}
|
||||
|
||||
self.engine?.send(str, datas: emitDatas)
|
||||
let packet = SocketPacket(type: nil, data: args, nsp: self.nsp, id: ack)
|
||||
var str:String
|
||||
|
||||
SocketParser.parseForEmit(packet)
|
||||
str = packet.createMessageForEvent(event)
|
||||
|
||||
if packet.type == SocketPacketType.BINARY_EVENT {
|
||||
self.engine?.send(str, withData: packet.binary)
|
||||
} else {
|
||||
if ack == nil {
|
||||
str = SocketEvent.createMessageForEvent(event, withArgs: items, hasBinary: false,
|
||||
withDatas: 0, toNamespace: self.nsp)
|
||||
} else {
|
||||
str = SocketEvent.createMessageForEvent(event, withArgs: items, hasBinary: false,
|
||||
withDatas: 0, toNamespace: self.nsp, wantsAck: ack)
|
||||
}
|
||||
|
||||
self.engine?.send(str)
|
||||
self.engine?.send(str, withData: nil)
|
||||
}
|
||||
}
|
||||
|
||||
// If the server wants to know that the client received data
|
||||
func emitAck(ack:Int, withData data:[AnyObject]?, withAckType ackType:Int) {
|
||||
dispatch_async(self.ackQueue) {[weak self] in
|
||||
if self == nil || !self!.connected || data == nil {
|
||||
func emitAck(ack:Int, withData args:[AnyObject]) {
|
||||
dispatch_async(self.emitQueue) {[weak self] in
|
||||
if self == nil || !self!.connected {
|
||||
return
|
||||
}
|
||||
|
||||
// println("sending ack: \(ack) \(data)")
|
||||
let (items, hasBinary, emitDatas) = SocketParser.parseEmitArgs(data!)
|
||||
let packet = SocketPacket(type: nil, data: args, nsp: self!.nsp, id: ack)
|
||||
var str:String
|
||||
|
||||
if !hasBinary {
|
||||
if self?.nsp == nil {
|
||||
str = SocketEvent.createAck(ack, withArgs: items,
|
||||
withAckType: 3, withNsp: "/")
|
||||
} else {
|
||||
str = SocketEvent.createAck(ack, withArgs: items,
|
||||
withAckType: 3, withNsp: self!.nsp!)
|
||||
}
|
||||
|
||||
self?.engine?.send(str)
|
||||
SocketParser.parseForEmit(packet)
|
||||
str = packet.createAck()
|
||||
|
||||
if packet.type == SocketPacketType.BINARY_ACK {
|
||||
self?.engine?.send(str, withData: packet.binary)
|
||||
} else {
|
||||
if self?.nsp == nil {
|
||||
str = SocketEvent.createAck(ack, withArgs: items,
|
||||
withAckType: 6, withNsp: "/", withBinary: emitDatas.count)
|
||||
} else {
|
||||
str = SocketEvent.createAck(ack, withArgs: items,
|
||||
withAckType: 6, withNsp: self!.nsp!, withBinary: emitDatas.count)
|
||||
}
|
||||
|
||||
self?.engine?.send(str, datas: emitDatas)
|
||||
self?.engine?.send(str, withData: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -333,8 +351,8 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
/**
|
||||
Causes an event to be handled. Only use if you know what you're doing.
|
||||
*/
|
||||
public func handleEvent(event:String, data:AnyObject?, isInternalMessage:Bool = false,
|
||||
wantsAck ack:Int? = nil, withAckType ackType:Int = 3) {
|
||||
public func handleEvent(event:String, data:[AnyObject]?, isInternalMessage:Bool = false,
|
||||
wantsAck ack:Int? = nil) {
|
||||
// println("Should do event: \(event) with data: \(data)")
|
||||
if !self.connected && !isInternalMessage {
|
||||
return
|
||||
@@ -342,48 +360,35 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
|
||||
if self.anyHandler != nil {
|
||||
dispatch_async(dispatch_get_main_queue()) {[weak self] in
|
||||
self?.anyHandler?((event, data))
|
||||
self?.anyHandler?(SocketAnyEvent(event: event, items: data))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
for handler in self.handlers {
|
||||
if handler.event == event {
|
||||
if data is NSArray {
|
||||
if ack != nil {
|
||||
handler.executeCallback(data as? NSArray, withAck: ack!,
|
||||
withAckType: ackType, withSocket: self)
|
||||
} else {
|
||||
handler.executeCallback(data as? NSArray)
|
||||
}
|
||||
if ack != nil {
|
||||
handler.executeCallback(data, withAck: ack!, withSocket: self)
|
||||
} 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)
|
||||
} else {
|
||||
handler.executeCallback(dataArr)
|
||||
}
|
||||
handler.executeCallback(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Should be removed and moved to SocketEngine
|
||||
func joinNamespace() {
|
||||
if self.nsp != nil {
|
||||
self.engine?.send("0/\(self.nsp!)")
|
||||
if self.nsp != "/" {
|
||||
self.engine?.send("0/\(self.nsp)", withData: nil)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Removes handler(s)
|
||||
*/
|
||||
public func off(event:String) {
|
||||
self.handlers = self.handlers.filter {$0.event == event ? false : true}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler for an event.
|
||||
*/
|
||||
@@ -395,7 +400,7 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
/**
|
||||
Adds a handler that will be called on every event.
|
||||
*/
|
||||
public func onAny(handler:(AnyHandler) -> Void) {
|
||||
public func onAny(handler:(SocketAnyEvent) -> Void) {
|
||||
self.anyHandler = handler
|
||||
}
|
||||
|
||||
@@ -415,10 +420,10 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
}
|
||||
|
||||
// Something happened while polling
|
||||
public func pollingDidFail(err:NSError?) {
|
||||
public func pollingDidFail(err:String) {
|
||||
if !self.reconnecting {
|
||||
self._connected = false
|
||||
self.handleEvent("reconnect", data: err?.localizedDescription, isInternalMessage: true)
|
||||
self.handleEvent("reconnect", data: [err], isInternalMessage: true)
|
||||
self.tryReconnect()
|
||||
}
|
||||
}
|
||||
@@ -430,7 +435,7 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
// We lost connection and should attempt to reestablish
|
||||
func tryReconnect() {
|
||||
if self.reconnectAttempts != -1 && self.currentReconnectAttempt + 1 > self.reconnectAttempts {
|
||||
self.didForceClose(message: "Reconnect Failed")
|
||||
self.didForceClose("Reconnect Failed")
|
||||
return
|
||||
} else if self.connected {
|
||||
self._connecting = false
|
||||
@@ -452,7 +457,7 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
}
|
||||
}
|
||||
|
||||
self.handleEvent("reconnectAttempt", data: self.reconnectAttempts - self.currentReconnectAttempt,
|
||||
self.handleEvent("reconnectAttempt", data: [self.reconnectAttempts - self.currentReconnectAttempt],
|
||||
isInternalMessage: true)
|
||||
|
||||
self.currentReconnectAttempt++
|
||||
@@ -464,13 +469,13 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
}
|
||||
|
||||
// Called when the socket is closed
|
||||
public func webSocketDidCloseWithCode(code:Int, reason:String, wasClean:Bool) {
|
||||
public func webSocketDidCloseWithCode(code:Int, reason:String) {
|
||||
self._connected = false
|
||||
self._connecting = false
|
||||
if self.closed || !self.reconnects {
|
||||
self.didForceClose(message: "WebSocket closed")
|
||||
} else {
|
||||
self.handleEvent("reconnect", data: reason, isInternalMessage: true)
|
||||
self.didForceClose("WebSocket closed")
|
||||
} else if !self.reconnecting {
|
||||
self.handleEvent("reconnect", data: [reason], isInternalMessage: true)
|
||||
self.tryReconnect()
|
||||
}
|
||||
}
|
||||
@@ -479,11 +484,11 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
public func webSocketDidFailWithError(error:NSError) {
|
||||
self._connected = false
|
||||
self._connecting = false
|
||||
self.handleEvent("error", data: error.localizedDescription, isInternalMessage: true)
|
||||
self.handleEvent("error", data: [error.localizedDescription], isInternalMessage: true)
|
||||
if self.closed || !self.reconnects {
|
||||
self.didForceClose(message: "WebSocket closed with an error \(error)")
|
||||
self.didForceClose("WebSocket closed with an error \(error)")
|
||||
} else if !self.reconnecting {
|
||||
self.handleEvent("reconnect", data: error.localizedDescription, isInternalMessage: true)
|
||||
self.handleEvent("reconnect", data: [error.localizedDescription], isInternalMessage: true)
|
||||
self.tryReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
//
|
||||
// SocketPacket.swift
|
||||
// Socket.IO-Swift
|
||||
//
|
||||
// Created by Erik Little on 1/18/15.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
enum SocketPacketType: Int {
|
||||
case CONNECT = 0
|
||||
case DISCONNECT = 1
|
||||
case EVENT = 2
|
||||
case ACK = 3
|
||||
case ERROR = 4
|
||||
case BINARY_EVENT = 5
|
||||
case BINARY_ACK = 6
|
||||
|
||||
init(str:String) {
|
||||
if let int = str.toInt() {
|
||||
self = SocketPacketType(rawValue: int)!
|
||||
} else {
|
||||
self = SocketPacketType(rawValue: 4)!
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SocketPacket {
|
||||
var binary = ContiguousArray<NSData>()
|
||||
var currentPlace = 0
|
||||
var data:[AnyObject]?
|
||||
var id:Int?
|
||||
var justAck = false
|
||||
var nsp = ""
|
||||
var placeholders:Int?
|
||||
var type:SocketPacketType?
|
||||
|
||||
init(type:SocketPacketType?, data:[AnyObject]? = nil, nsp:String = "",
|
||||
placeholders:Int? = nil, id:Int? = nil) {
|
||||
self.type = type
|
||||
self.data = data
|
||||
self.nsp = nsp
|
||||
self.placeholders = placeholders
|
||||
self.id = id
|
||||
}
|
||||
|
||||
func getEvent() -> String {
|
||||
return data?.removeAtIndex(0) as String
|
||||
}
|
||||
|
||||
func addData(data:NSData) -> Bool {
|
||||
func checkDoEvent() -> Bool {
|
||||
if self.placeholders == self.currentPlace {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if checkDoEvent() {
|
||||
return true
|
||||
}
|
||||
|
||||
self.binary.append(data)
|
||||
self.currentPlace++
|
||||
|
||||
if checkDoEvent() {
|
||||
self.currentPlace = 0
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func createMessageForEvent(event:String) -> String {
|
||||
var message:String
|
||||
var jsonSendError:NSError?
|
||||
|
||||
if self.binary.count == 0 {
|
||||
self.type = SocketPacketType.EVENT
|
||||
|
||||
if self.nsp == "/" {
|
||||
if self.id == nil {
|
||||
message = "2[\"\(event)\""
|
||||
} else {
|
||||
message = "2\(self.id!)[\"\(event)\""
|
||||
}
|
||||
} else {
|
||||
if self.id == nil {
|
||||
message = "2/\(self.nsp),[\"\(event)\""
|
||||
} else {
|
||||
message = "2/\(self.nsp),\(self.id!)[\"\(event)\""
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.type = SocketPacketType.BINARY_EVENT
|
||||
|
||||
if self.nsp == "/" {
|
||||
if self.id == nil {
|
||||
message = "5\(self.binary.count)-[\"\(event)\""
|
||||
} else {
|
||||
message = "5\(self.binary.count)-\(self.id!)[\"\(event)\""
|
||||
}
|
||||
} else {
|
||||
if self.id == nil {
|
||||
message = "5\(self.binary.count)-/\(self.nsp),[\"\(event)\""
|
||||
} else {
|
||||
message = "5\(self.binary.count)-/\(self.nsp),\(self.id!)[\"\(event)\""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return self.completeMessage(message)
|
||||
}
|
||||
|
||||
func createAck() -> String {
|
||||
var msg:String
|
||||
|
||||
if self.binary.count == 0 {
|
||||
self.type = SocketPacketType.ACK
|
||||
|
||||
if nsp == "/" {
|
||||
msg = "3\(self.id!)["
|
||||
} else {
|
||||
msg = "3/\(self.nsp),\(self.id!)["
|
||||
}
|
||||
} else {
|
||||
self.type = SocketPacketType.BINARY_ACK
|
||||
|
||||
if nsp == "/" {
|
||||
msg = "6\(self.binary.count)-\(self.id!)["
|
||||
} else {
|
||||
msg = "6\(self.binary.count)-/\(self.nsp),\(self.id!)["
|
||||
}
|
||||
}
|
||||
|
||||
return self.completeMessage(msg, ack: true)
|
||||
}
|
||||
|
||||
func completeMessage(var message:String, ack:Bool = false) -> String {
|
||||
var err:NSError?
|
||||
|
||||
if self.data == nil || self.data!.count == 0 {
|
||||
return message + "]"
|
||||
} else if !ack {
|
||||
message += ","
|
||||
}
|
||||
|
||||
for arg in self.data! {
|
||||
|
||||
if arg is NSDictionary || arg is [AnyObject] {
|
||||
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
|
||||
options: NSJSONWritingOptions(0), error: &err)
|
||||
let jsonString = NSString(data: jsonSend!, encoding: NSUTF8StringEncoding)
|
||||
|
||||
message += jsonString! as String
|
||||
message += ","
|
||||
continue
|
||||
}
|
||||
|
||||
if arg is String {
|
||||
message += "\"\(arg)\""
|
||||
message += ","
|
||||
continue
|
||||
}
|
||||
|
||||
message += "\(arg)"
|
||||
message += ","
|
||||
}
|
||||
|
||||
if message != "" {
|
||||
message.removeAtIndex(message.endIndex.predecessor())
|
||||
}
|
||||
|
||||
return message + "]"
|
||||
}
|
||||
|
||||
func fillInPlaceholders() {
|
||||
var newArr = NSMutableArray(array: self.data!)
|
||||
|
||||
for i in 0..<self.data!.count {
|
||||
if let str = self.data?[i] as? String {
|
||||
if let num = str["~~(\\d)"].groups() {
|
||||
newArr[i] = self.binary[num[1].toInt()!]
|
||||
}
|
||||
} else if self.data?[i] is NSDictionary || self.data?[i] is NSArray {
|
||||
newArr[i] = self._fillInPlaceholders(self.data![i])
|
||||
}
|
||||
}
|
||||
|
||||
self.data = newArr
|
||||
}
|
||||
|
||||
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
|
||||
if let str = data as? String {
|
||||
if let num = str["~~(\\d)"].groups() {
|
||||
return self.binary[num[1].toInt()!]
|
||||
} else {
|
||||
return str
|
||||
}
|
||||
} else if let dict = data as? NSDictionary {
|
||||
var newDict = NSMutableDictionary(dictionary: dict)
|
||||
|
||||
for (key, value) in dict {
|
||||
newDict[key as NSCopying] = _fillInPlaceholders(value)
|
||||
}
|
||||
|
||||
return newDict
|
||||
} else if let arr = data as? NSArray {
|
||||
var newArr = NSMutableArray(array: arr)
|
||||
|
||||
for i in 0..<arr.count {
|
||||
newArr[i] = _fillInPlaceholders(arr[i])
|
||||
}
|
||||
|
||||
return newArr
|
||||
} else {
|
||||
return data
|
||||
}
|
||||
}
|
||||
}
|
||||
+177
-294
@@ -22,63 +22,145 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
private let shredder = SocketParser.PacketShredder()
|
||||
|
||||
class SocketParser {
|
||||
// Parse an NSArray looking for binary data
|
||||
class func parseArray(arr:NSArray, var currentPlaceholder:Int) -> (NSArray, Bool, [NSData]) {
|
||||
var replacementArr = [AnyObject](count: arr.count, repeatedValue: 1)
|
||||
var hasBinary = false
|
||||
var arrayDatas = [NSData]()
|
||||
// Translation of socket.io-parser#deconstructPacket
|
||||
private class PacketShredder {
|
||||
var buf = ContiguousArray<NSData>()
|
||||
|
||||
for g in 0..<arr.count {
|
||||
if arr[g] is NSData {
|
||||
hasBinary = true
|
||||
currentPlaceholder++
|
||||
let sendData = arr[g] as NSData
|
||||
func shred(data:AnyObject) -> AnyObject {
|
||||
if let bin = data as? NSData {
|
||||
let placeholder = ["_placeholder" :true, "num": buf.count]
|
||||
|
||||
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)
|
||||
buf.append(bin)
|
||||
|
||||
if hadBinary {
|
||||
hasBinary = true
|
||||
currentPlaceholder += dictArrs.count
|
||||
replacementArr[g] = nestDict
|
||||
arrayDatas.extend(dictArrs)
|
||||
} else {
|
||||
replacementArr[g] = dict
|
||||
return placeholder
|
||||
} else if let arr = data as? NSArray {
|
||||
var newArr = NSMutableArray(array: arr)
|
||||
|
||||
for i in 0..<arr.count {
|
||||
newArr[i] = shred(arr[i])
|
||||
}
|
||||
} else if let nestArr = arr[g] as? NSArray {
|
||||
// Recursive
|
||||
let (nested, hadBinary, nestDatas) = self.parseArray(nestArr,
|
||||
currentPlaceholder: currentPlaceholder)
|
||||
|
||||
if hadBinary {
|
||||
hasBinary = true
|
||||
currentPlaceholder += nestDatas.count
|
||||
replacementArr[g] = nested
|
||||
arrayDatas.extend(nestDatas)
|
||||
} else {
|
||||
replacementArr[g] = arr[g]
|
||||
return newArr
|
||||
} else if let dict = data as? NSDictionary {
|
||||
var newDict = NSMutableDictionary(dictionary: dict)
|
||||
|
||||
for (key, value) in newDict {
|
||||
newDict[key as NSCopying] = shred(value)
|
||||
}
|
||||
|
||||
return newDict
|
||||
} else {
|
||||
replacementArr[g] = arr[g]
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
return (replacementArr, hasBinary, arrayDatas)
|
||||
func deconstructPacket(packet:SocketPacket) {
|
||||
if packet.data == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var data = packet.data!
|
||||
|
||||
for i in 0..<data.count {
|
||||
if data[i] is NSArray || data[i] is NSDictionary {
|
||||
data[i] = shred(data[i])
|
||||
} else if let bin = data[i] as? NSData {
|
||||
data[i] = ["_placeholder" :true, "num": buf.count]
|
||||
buf.append(bin)
|
||||
}
|
||||
}
|
||||
|
||||
packet.data = data
|
||||
packet.binary = buf
|
||||
buf.removeAll(keepCapacity: true)
|
||||
}
|
||||
}
|
||||
|
||||
// Translation of socket.io-client#decodeString
|
||||
class func parseString(str:String) -> SocketPacket? {
|
||||
let arr = Array(str)
|
||||
let type = String(arr[0])
|
||||
|
||||
if arr.count == 1 {
|
||||
return SocketPacket(type: SocketPacketType(str: type))
|
||||
}
|
||||
|
||||
var id = nil as Int?
|
||||
var nsp = ""
|
||||
var i = 0
|
||||
var placeholders = -1
|
||||
|
||||
if type == "5" || type == "6" {
|
||||
var buf = ""
|
||||
|
||||
while arr[++i] != "-" {
|
||||
buf += String(arr[i])
|
||||
if i == arr.count {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if buf.toInt() == nil || arr[i] != "-" {
|
||||
NSLog("Error parsing \(str)")
|
||||
return nil
|
||||
} else {
|
||||
placeholders = buf.toInt()!
|
||||
}
|
||||
}
|
||||
|
||||
if arr[i + 1] == "/" {
|
||||
while ++i < arr.count {
|
||||
let c = arr[i]
|
||||
|
||||
if c == "," {
|
||||
break
|
||||
}
|
||||
|
||||
nsp += String(c)
|
||||
}
|
||||
}
|
||||
|
||||
if i + 1 >= arr.count {
|
||||
return SocketPacket(type: SocketPacketType(str: type),
|
||||
nsp: nsp, placeholders: placeholders, id: id)
|
||||
}
|
||||
|
||||
let next = String(arr[i + 1])
|
||||
|
||||
if next.toInt() != nil {
|
||||
var c = ""
|
||||
while ++i < arr.count {
|
||||
if let int = String(arr[i]).toInt() {
|
||||
c += String(arr[i])
|
||||
} else {
|
||||
--i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
id = c.toInt()
|
||||
}
|
||||
|
||||
if i + 1 < arr.count {
|
||||
let d = String(arr[++i...arr.count-1])
|
||||
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
|
||||
|
||||
let data = SocketParser.parseData(noPlaceholders) as [AnyObject]
|
||||
|
||||
return SocketPacket(type: SocketPacketType(str: type), data: data,
|
||||
nsp: nsp, placeholders: placeholders, id: id)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Parses data for events
|
||||
class func parseData(data:String?) -> AnyObject? {
|
||||
if data == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
class func parseData(data:String) -> AnyObject? {
|
||||
var err:NSError?
|
||||
let stringData = data!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
||||
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
||||
let parsed:AnyObject? = NSJSONSerialization.JSONObjectWithData(stringData!,
|
||||
options: NSJSONReadingOptions.AllowFragments, error: &err)
|
||||
|
||||
@@ -90,176 +172,62 @@ class SocketParser {
|
||||
return parsed
|
||||
}
|
||||
|
||||
class func parseEmitArgs(args:[AnyObject]) -> ([AnyObject], Bool, [NSData]) {
|
||||
var items = [AnyObject](count: args.count, repeatedValue: 1)
|
||||
var currentPlaceholder = -1
|
||||
var hasBinary = false
|
||||
var emitDatas = [NSData]()
|
||||
|
||||
for i in 0..<args.count {
|
||||
if let dict = args[i] as? NSDictionary {
|
||||
// Check for binary data
|
||||
let (newDict, hadBinary, binaryDatas) = self.parseNSDictionary(dict,
|
||||
currentPlaceholder: currentPlaceholder)
|
||||
if hadBinary {
|
||||
currentPlaceholder += binaryDatas.count
|
||||
emitDatas.extend(binaryDatas)
|
||||
hasBinary = true
|
||||
items[i] = newDict
|
||||
} else {
|
||||
items[i] = dict
|
||||
}
|
||||
} else if let arr = args[i] as? NSArray {
|
||||
// arg is array, check for binary
|
||||
let (replace, hadData, newDatas) = self.parseArray(arr,
|
||||
currentPlaceholder: currentPlaceholder)
|
||||
|
||||
if hadData {
|
||||
hasBinary = true
|
||||
currentPlaceholder += newDatas.count
|
||||
|
||||
for data in newDatas {
|
||||
emitDatas.append(data)
|
||||
}
|
||||
|
||||
items[i] = replace
|
||||
} else {
|
||||
items[i] = arr
|
||||
}
|
||||
} else if let binaryData = args[i] as? NSData {
|
||||
// args is just binary
|
||||
hasBinary = true
|
||||
|
||||
currentPlaceholder++
|
||||
items[i] = ["_placeholder": true, "num": currentPlaceholder]
|
||||
emitDatas.append(binaryData)
|
||||
} else {
|
||||
items[i] = args[i]
|
||||
}
|
||||
}
|
||||
|
||||
return (items, hasBinary, emitDatas)
|
||||
}
|
||||
|
||||
// Parses a NSDictionary, looking for NSData objects
|
||||
class func parseNSDictionary(dict:NSDictionary, var currentPlaceholder:Int) -> (NSDictionary, Bool, [NSData]) {
|
||||
var returnDict = NSMutableDictionary()
|
||||
var hasBinary = false
|
||||
var returnDatas = [NSData]()
|
||||
|
||||
for (key, value) in dict {
|
||||
if let binaryData = value as? NSData {
|
||||
currentPlaceholder++
|
||||
hasBinary = true
|
||||
returnDatas.append(binaryData)
|
||||
returnDict[key as String] = ["_placeholder": true, "num": currentPlaceholder]
|
||||
} else if let arr = value as? NSArray {
|
||||
let (replace, hadBinary, arrDatas) = self.parseArray(arr, currentPlaceholder: currentPlaceholder)
|
||||
|
||||
if hadBinary {
|
||||
hasBinary = true
|
||||
returnDict[key as String] = replace
|
||||
currentPlaceholder += arrDatas.count
|
||||
returnDatas.extend(arrDatas)
|
||||
} else {
|
||||
returnDict[key as String] = arr
|
||||
}
|
||||
} else if let dict = value as? NSDictionary {
|
||||
// Recursive
|
||||
let (nestDict, hadBinary, nestDatas) = self.parseNSDictionary(dict, currentPlaceholder: currentPlaceholder)
|
||||
|
||||
if hadBinary {
|
||||
hasBinary = true
|
||||
returnDict[key as String] = nestDict
|
||||
currentPlaceholder += nestDatas.count
|
||||
returnDatas.extend(nestDatas)
|
||||
} else {
|
||||
returnDict[key as String] = dict
|
||||
}
|
||||
} else {
|
||||
returnDict[key as String] = value
|
||||
}
|
||||
}
|
||||
|
||||
return (returnDict, hasBinary, returnDatas)
|
||||
class func parseForEmit(packet:SocketPacket) {
|
||||
shredder.deconstructPacket(packet)
|
||||
}
|
||||
|
||||
// Parses messages recieved
|
||||
class func parseSocketMessage(var stringMessage:String, socket:SocketIOClient) {
|
||||
class func parseSocketMessage(stringMessage:String, socket:SocketIOClient) {
|
||||
if stringMessage == "" {
|
||||
return
|
||||
}
|
||||
|
||||
// NSLog(stringMessage)
|
||||
|
||||
// Check for successful namepsace connect
|
||||
if socket.nsp != nil {
|
||||
if stringMessage == "0/\(socket.nsp!)" {
|
||||
socket.didConnect()
|
||||
return
|
||||
func checkNSP(nsp:String) -> Bool {
|
||||
if nsp == "" && socket.nsp != "/" {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if stringMessage == "0" {
|
||||
if socket.nsp != nil {
|
||||
// Join namespace
|
||||
socket.joinNamespace()
|
||||
let p = parseString(stringMessage) as SocketPacket!
|
||||
|
||||
if p.type == SocketPacketType.EVENT {
|
||||
if checkNSP(p.nsp) {
|
||||
return
|
||||
}
|
||||
|
||||
socket.handleEvent(p.getEvent(), data: p.data,
|
||||
isInternalMessage: false, wantsAck: p.id)
|
||||
} else if p.type == SocketPacketType.ACK {
|
||||
if checkNSP(p.nsp) {
|
||||
return
|
||||
}
|
||||
|
||||
socket.handleAck(p.id!, data: p.data)
|
||||
} else if p.type == SocketPacketType.BINARY_EVENT {
|
||||
if checkNSP(p.nsp) {
|
||||
return
|
||||
}
|
||||
|
||||
socket.waitingData.append(p)
|
||||
} else if p.type == SocketPacketType.BINARY_ACK {
|
||||
if checkNSP(p.nsp) {
|
||||
return
|
||||
}
|
||||
|
||||
p.justAck = true
|
||||
socket.waitingData.append(p)
|
||||
} else if p.type == SocketPacketType.CONNECT {
|
||||
if p.nsp == "" && socket.nsp != "/" {
|
||||
socket.joinNamespace()
|
||||
} else if p.nsp != "" && socket.nsp == "/" {
|
||||
socket.didConnect()
|
||||
} else {
|
||||
socket.didConnect()
|
||||
return
|
||||
}
|
||||
} else if stringMessage == "1" {
|
||||
socket.didForceClose(message: "Got disconnect")
|
||||
return
|
||||
}
|
||||
|
||||
if stringMessage.hasPrefix("5") || stringMessage.hasPrefix("6") {
|
||||
// Check for message with binary placeholders
|
||||
self.parseBinaryMessage(stringMessage, socket: socket)
|
||||
return
|
||||
}
|
||||
|
||||
let type = stringMessage.removeAtIndex(stringMessage.startIndex)
|
||||
|
||||
if type == "2" {
|
||||
if let groups = stringMessage["(\\/(\\w*))?,?(\\d*)?\\[\"(.*?)\",?(.*?)?\\]$",
|
||||
NSRegularExpressionOptions.DotMatchesLineSeparators].groups() {
|
||||
let namespace = groups[2]
|
||||
let ackNum = groups[3]
|
||||
let event = groups[4]
|
||||
let data = "[\(groups[5])]"
|
||||
|
||||
if namespace == "" && socket.nsp != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if let parsed:AnyObject = self.parseData(data) {
|
||||
if ackNum == "" {
|
||||
socket.handleEvent(event, data: parsed)
|
||||
} else {
|
||||
socket.currentAck = ackNum.toInt()!
|
||||
socket.handleEvent(event, data: parsed, isInternalMessage: false,
|
||||
wantsAck: ackNum.toInt(), withAckType: 3)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if type == "3" {
|
||||
if let ackGroup = stringMessage["(\\/(\\w*))?,?(\\d*)?\\[(.*?)?\\]$",
|
||||
NSRegularExpressionOptions.DotMatchesLineSeparators].groups() {
|
||||
let nsp = ackGroup[2]
|
||||
let ackNum = ackGroup[3]
|
||||
let ackData:AnyObject? = self.parseData("[\(ackGroup[4])]")
|
||||
|
||||
if nsp == "" && socket.nsp != nil {
|
||||
return
|
||||
}
|
||||
|
||||
socket.handleAck(ackNum.toInt()!, data: ackData)
|
||||
}
|
||||
} else {
|
||||
NSLog("Error in parsing message: %s", stringMessage)
|
||||
return
|
||||
} else if p.type == SocketPacketType.DISCONNECT {
|
||||
socket.didForceClose("Got Disconnect")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,103 +242,18 @@ class SocketParser {
|
||||
|
||||
let shouldExecute = socket.waitingData[0].addData(data)
|
||||
|
||||
if shouldExecute {
|
||||
let socketEvent = socket.waitingData.removeAtIndex(0)
|
||||
var event = socketEvent.event
|
||||
var parsedArgs:AnyObject? = self.parseData(socketEvent.args as? String)
|
||||
|
||||
if let args:AnyObject = parsedArgs {
|
||||
let filledInArgs:AnyObject = socketEvent.fillInPlaceholders(args)
|
||||
|
||||
if socketEvent.justAck! {
|
||||
// Should handle ack
|
||||
socket.handleAck(socketEvent.ack!, data: filledInArgs)
|
||||
return
|
||||
}
|
||||
|
||||
// Should do event
|
||||
if socketEvent.ack != nil {
|
||||
socket.handleEvent(event, data: filledInArgs, isInternalMessage: false,
|
||||
wantsAck: socketEvent.ack!, withAckType: 6)
|
||||
} else {
|
||||
socket.handleEvent(event, data: filledInArgs)
|
||||
}
|
||||
} else {
|
||||
let filledInArgs:AnyObject = socketEvent.fillInPlaceholders()
|
||||
|
||||
// Should handle ack
|
||||
if socketEvent.justAck! {
|
||||
socket.handleAck(socketEvent.ack!, data: filledInArgs)
|
||||
return
|
||||
}
|
||||
|
||||
// Should handle ack
|
||||
if socketEvent.ack != nil {
|
||||
socket.handleEvent(event, data: filledInArgs, isInternalMessage: false,
|
||||
wantsAck: socketEvent.ack!, withAckType: 6)
|
||||
} else {
|
||||
socket.handleEvent(event, data: filledInArgs)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tries to parse a message that contains binary
|
||||
class func parseBinaryMessage(var message:String, socket:SocketIOClient) {
|
||||
// NSLog(message)
|
||||
|
||||
let type = message.removeAtIndex(message.startIndex)
|
||||
|
||||
if type == "5" {
|
||||
if let groups = message["^(\\d*)-(\\/(\\w*))?,?(\\d*)?\\[\"(.*?)\",?(.*)?\\]$",
|
||||
NSRegularExpressionOptions.DotMatchesLineSeparators].groups() {
|
||||
let numberOfPlaceholders = groups[1]
|
||||
let namespace = groups[3]
|
||||
let ackNum = groups[4]
|
||||
let event = groups[5]
|
||||
let mutMessageObject = groups[6]
|
||||
|
||||
if namespace == "" && socket.nsp != nil {
|
||||
return
|
||||
}
|
||||
|
||||
let placeholdersRemoved = mutMessageObject["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"]
|
||||
~= "\"~~$2\""
|
||||
|
||||
var mes:SocketEvent
|
||||
if ackNum == "" {
|
||||
mes = SocketEvent(event: event, args: placeholdersRemoved,
|
||||
placeholders: numberOfPlaceholders.toInt()!)
|
||||
} else {
|
||||
socket.currentAck = ackNum.toInt()!
|
||||
mes = SocketEvent(event: event, args: placeholdersRemoved,
|
||||
placeholders: numberOfPlaceholders.toInt()!, ackNum: ackNum.toInt())
|
||||
}
|
||||
|
||||
socket.waitingData.append(mes)
|
||||
}
|
||||
} else if type == "6" {
|
||||
if let groups = message["^(\\d*)-(\\/(\\w*))?,?(\\d*)?\\[(.*?)?\\]$",
|
||||
NSRegularExpressionOptions.DotMatchesLineSeparators].groups() {
|
||||
let numberOfPlaceholders = groups[1]
|
||||
let namespace = groups[3]
|
||||
let ackNum = groups[4]
|
||||
let mutMessageObject = groups[5]
|
||||
|
||||
if namespace == "" && socket.nsp != nil {
|
||||
return
|
||||
}
|
||||
let placeholdersRemoved = mutMessageObject["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"]
|
||||
~= "\"~~$2\""
|
||||
|
||||
let event = SocketEvent(event: "", args: placeholdersRemoved,
|
||||
placeholders: numberOfPlaceholders.toInt()!, ackNum: ackNum.toInt(), justAck: true)
|
||||
|
||||
socket.waitingData.append(event)
|
||||
}
|
||||
} else {
|
||||
NSLog("Error in parsing binary message: %s", message)
|
||||
if !shouldExecute {
|
||||
return
|
||||
}
|
||||
|
||||
let packet = socket.waitingData.removeAtIndex(0)
|
||||
packet.fillInPlaceholders()
|
||||
|
||||
if !packet.justAck {
|
||||
socket.handleEvent(packet.getEvent(), data: packet.data,
|
||||
wantsAck: packet.id)
|
||||
} else {
|
||||
socket.handleAck(packet.id!, data: packet.data)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user