Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0c3e25ef3c | ||
|
|
ac28c7541e | ||
|
|
fcc202ab04 | ||
|
|
c2d488e35c | ||
|
|
eb9d2bc744 | ||
|
|
a4e81fee6a | ||
|
|
9489676009 | ||
|
|
6e56869ef0 | ||
|
|
3ebc596ab8 | ||
|
|
1349b01b2b | ||
|
|
a1f24ff281 | ||
|
|
838dade0fa | ||
|
|
d4470a9084 | ||
|
|
affd792334 | ||
|
|
38163d29cb | ||
|
|
2952120fc1 | ||
|
|
7641ffef41 | ||
|
|
58d2693910 | ||
|
|
dd28b1747c | ||
|
|
e90ecb81be | ||
|
|
060060f5c2 | ||
|
|
f7b064d80f | ||
|
|
01a699c7c6 |
No files matched your search
@@ -1,13 +1,50 @@
|
||||
Socket.IO-Client-Swift
|
||||
======================
|
||||
#Socket.IO-Client-Swift
|
||||
Socket.IO-client for iOS/OS X.
|
||||
|
||||
Socket.IO-client for Swift. Supports ws/wss/polling connections and binary. For socket.io 1.0+ and Swift 1.1.
|
||||
##Example
|
||||
```swift
|
||||
let socket = SocketIOClient(socketURL: "localhost:8080")
|
||||
|
||||
For Swift 1.2 use the 1.2 branch.
|
||||
socket.on("connect") {data, ack in
|
||||
println("socket connected")
|
||||
}
|
||||
|
||||
Installation
|
||||
============
|
||||
socket.on("currentAmount") {data, ack in
|
||||
if let cur = data?[0] as? Double {
|
||||
socket.emitWithAck("canUpdate", cur)(timeout: 0) {data in
|
||||
socket.emit("update", ["amount": cur + 2.50])
|
||||
}
|
||||
|
||||
ack?("Got your currentAmount", "dude")
|
||||
}
|
||||
}
|
||||
|
||||
// Connect
|
||||
socket.connect()
|
||||
```
|
||||
|
||||
##Objective-C Example
|
||||
```objective-c
|
||||
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" options:nil];
|
||||
|
||||
[socket on: @"connect" callback: ^(NSArray* data, void (^ack)(NSArray*)) {
|
||||
NSLog(@"connected");
|
||||
[socket emitObjc:@"echo" withItems:@[@"echo test"]];
|
||||
[socket emitWithAckObjc:@"ackack" withItems:@[@1]](10, ^(NSArray* data) {
|
||||
NSLog(@"Got ack");
|
||||
});
|
||||
}];
|
||||
|
||||
```
|
||||
|
||||
##Features
|
||||
- Supports socket.io 1.0+
|
||||
- Supports binary
|
||||
- Supports Polling and WebSockets
|
||||
- Supports TLS/SSL
|
||||
- Can be used from Objective-C
|
||||
|
||||
##Installation
|
||||
Manually (iOS 7+)
|
||||
-----------------
|
||||
1. Copy the SwiftIO folder into your Xcode project!
|
||||
@@ -36,24 +73,34 @@ Import in your swift file:
|
||||
import Socket_IO_Client_Swift
|
||||
```
|
||||
|
||||
API
|
||||
===
|
||||
##API
|
||||
Constructors
|
||||
-----------
|
||||
`init(socketURL: String, opts:NSDictionary? = nil)` - Constructs a new client for the given URL. opts can be omitted (will use default values. See example)
|
||||
`init(socketURL: String, opts:NSDictionary? = nil)` - Constructs a new client for the given URL. opts can be omitted (will use default values)
|
||||
|
||||
`convenience init(socketURL: String, options:NSDictionary?)` - Same as above, but meant for Objective-C. See Objective-C Example.
|
||||
|
||||
Options
|
||||
-------
|
||||
- `reconnects: Bool` Default is `true`
|
||||
- `reconnectAttempts: Int` Default is `-1` (infinite tries)
|
||||
- `reconnectWait: Int` Default is `10`
|
||||
- `forcePolling: Bool` Default is `false`. `true` forces the client to use xhr-polling.
|
||||
- `forceWebsockets: Bool` Default is `false`. `true` forces the client to use WebSockets.
|
||||
- `nsp: String` Default is `"/"`
|
||||
- `cookies: [NSHTTPCookie]?` An array of NSHTTPCookies. Passed during the handshake. Default is nil.
|
||||
|
||||
Methods
|
||||
-------
|
||||
1. `socket.on(name:String, callback:((data:NSArray?, ack:AckEmitter?) -> Void))` - Adds a handler for an event. Items are passed by an array. `ack` can be used to send an ack when one is requested. See example.
|
||||
2. `socket.onAny(callback:((event:String, items:AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
|
||||
3. `socket.emit(event:String, _ 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, _ 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(#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.
|
||||
1. `on(name:String, callback:((data:NSArray?, ack:AckEmitter?) -> Void))` - Adds a handler for an event. Items are passed by an array. `ack` can be used to send an ack when one is requested. See example.
|
||||
2. `onAny(callback:((event:String, items:AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
|
||||
3. `emit(event:String, _ items:AnyObject...)` - Sends a message. Can send multiple items.
|
||||
4. `emitObjc(event:String, withItems items:[AnyObject])` - `emit` for Objective-C
|
||||
5. `emitWithAck(event:String, _ items:AnyObject...) -> (timeout:UInt64, callback:(NSArray?) -> Void) -> Void` - Sends a message that requests an acknowledgement from the server. Returns a function which you can use to add a handler. See example. Note: The message is not sent until you call the returned function.
|
||||
6. `emitWithAckObjc(event:String, withItems items:[AnyObject]) -> (UInt64, (NSArray?) -> Void) -> Void` - `emitWithAck` for Objective-C. Note: The message is not sent until you call the returned function.
|
||||
7. `connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
|
||||
8. `connectWithParams(params:[String: AnyObject])` - Establishes a connection to the server passing the specified params. A "connect" event is fired upon successful connection.
|
||||
9. `close(#fast:Bool)` - Closes the socket. Once a socket is closed it should not be reopened. Pass true to fast if you're closing from a background task.
|
||||
|
||||
Events
|
||||
------
|
||||
@@ -63,87 +110,8 @@ Events
|
||||
4. `reconnect` - Emitted when the connection is starting to reconnect.
|
||||
5. `reconnectAttempt` - Emitted when attempting to reconnect.
|
||||
|
||||
Example
|
||||
=======
|
||||
```swift
|
||||
// opts can be omitted, will use default values
|
||||
let socket = SocketIOClient(socketURL: "https://localhost:8080", opts: [
|
||||
"reconnects": true, // Default is true
|
||||
"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 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
|
||||
])
|
||||
|
||||
// Called on every event
|
||||
socket.onAny {println("got event: \($0.event) with items \($0.items)")}
|
||||
|
||||
// Socket Events
|
||||
socket.on("connect") {data, ack in
|
||||
println("socket connected")
|
||||
|
||||
// Sending messages
|
||||
socket.emit("testEcho")
|
||||
|
||||
socket.emit("testObject", [
|
||||
"data": true
|
||||
])
|
||||
|
||||
// Sending multiple items per message
|
||||
socket.emit("multTest", [1], 1.4, 1, "true",
|
||||
true, ["test": "foo"], "bar")
|
||||
}
|
||||
|
||||
// Requesting acks, and responding to acks
|
||||
socket.on("ackEvent") {data, ack in
|
||||
if let str = data?[0] as? String {
|
||||
println("Got ackEvent")
|
||||
}
|
||||
|
||||
// data is an array
|
||||
if let int = data?[1] as? Int {
|
||||
println("Got int")
|
||||
}
|
||||
|
||||
// You can specify a custom timeout interval. 0 means no timeout.
|
||||
socket.emitWithAck("ackTest", "test").onAck(0) {data in
|
||||
println(data?[0])
|
||||
}
|
||||
|
||||
ack?("Got your event", "dude")
|
||||
}
|
||||
|
||||
socket.on("jsonTest") {data, ack in
|
||||
if let json = data?[0] as? NSDictionary {
|
||||
println(json["test"]!) // foo bar
|
||||
}
|
||||
}
|
||||
|
||||
// Connecting
|
||||
socket.connect()
|
||||
```
|
||||
|
||||
Objective-C Example
|
||||
===================
|
||||
```objective-c
|
||||
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" options:nil];
|
||||
|
||||
[socket on: @"connect" callback: ^(NSArray* data, void (^ack)(NSArray*)) {
|
||||
NSLog(@"connected");
|
||||
[socket emitObjc:@"echo" withItems:@[@"echo test"]];
|
||||
[[socket emitWithAckObjc:@"ackack" withItems:@[@"test"]] onAck:0 withCallback:^(NSArray* data) {
|
||||
NSLog(@"Got data");
|
||||
}];
|
||||
}];
|
||||
|
||||
```
|
||||
|
||||
Detailed Example
|
||||
================
|
||||
##Detailed Example
|
||||
A more detailed example can be found [here](https://github.com/nuclearace/socket.io-client-swift-example)
|
||||
|
||||
License
|
||||
=======
|
||||
##License
|
||||
MIT
|
||||
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "Socket.IO-Client-Swift"
|
||||
s.version = "1.4.4"
|
||||
s.version = "1.5.2"
|
||||
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.4.4' }
|
||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v1.5.2' }
|
||||
s.source_files = "SwiftIO/**/*.swift"
|
||||
s.requires_arc = true
|
||||
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
//
|
||||
// SocketAckHandler.swift
|
||||
// Socket.IO-Swift
|
||||
// SocketAckMap.swift
|
||||
// SocketIO-Swift
|
||||
//
|
||||
// Created by Erik Little on 4/3/15.
|
||||
//
|
||||
// Created by Erik Little on 2/14/15.
|
||||
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
@@ -24,46 +24,36 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
public typealias AckCallback = (NSArray?) -> Void
|
||||
|
||||
@objc public class SocketAckHandler {
|
||||
let ackNum:Int!
|
||||
let event:String!
|
||||
var acked = false
|
||||
var callback:AckCallback?
|
||||
weak var socket:SocketIOClient?
|
||||
public typealias AckCallback = @objc_block (NSArray?) -> Void
|
||||
public typealias OnAckCallback = (timeout:UInt64, callback:AckCallback) -> Void
|
||||
|
||||
struct SocketAckMap {
|
||||
private var acks = [Int: AckCallback]()
|
||||
private var waiting = [Int: Bool]()
|
||||
|
||||
init(event:String, ackNum:Int = 0, socket:SocketIOClient) {
|
||||
self.ackNum = ackNum
|
||||
self.event = event
|
||||
self.socket = socket
|
||||
mutating func addAck(ack:Int, callback:AckCallback) {
|
||||
waiting[ack] = true
|
||||
acks[ack] = callback
|
||||
}
|
||||
|
||||
public func onAck(timeout:UInt64, withCallback callback:AckCallback) {
|
||||
self.callback = callback
|
||||
mutating func executeAck(ack:Int, items:[AnyObject]?) {
|
||||
let callback = acks[ack]
|
||||
waiting[ack] = false
|
||||
|
||||
|
||||
if timeout != 0 {
|
||||
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
|
||||
dispatch_after(time, dispatch_get_main_queue()) {[weak self] in
|
||||
if self == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if !self!.acked {
|
||||
self?.executeAck(["No ACK"])
|
||||
self?.socket?.removeAck(self!)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func executeAck(data:NSArray?) {
|
||||
dispatch_async(dispatch_get_main_queue()) {[weak self, cb = self.callback] in
|
||||
self?.acked = true
|
||||
cb?(data)
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
callback?(items)
|
||||
return
|
||||
}
|
||||
|
||||
acks.removeValueForKey(ack)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func timeoutAck(ack:Int) {
|
||||
if waiting[ack] != nil && waiting[ack]! {
|
||||
acks[ack]?(["NO ACK"])
|
||||
}
|
||||
|
||||
acks.removeValueForKey(ack)
|
||||
waiting.removeValueForKey(ack)
|
||||
}
|
||||
}
|
||||
+88
-40
@@ -33,7 +33,7 @@ extension String {
|
||||
private typealias Probe = (msg:String, type:PacketType, data:ContiguousArray<NSData>?)
|
||||
private typealias ProbeWaitQueue = [Probe]
|
||||
|
||||
public enum PacketType: String {
|
||||
public enum PacketType:String {
|
||||
case OPEN = "0"
|
||||
case CLOSE = "1"
|
||||
case PING = "2"
|
||||
@@ -44,7 +44,6 @@ public enum PacketType: String {
|
||||
}
|
||||
|
||||
public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
unowned let client:SocketEngineClient
|
||||
private let workQueue = NSOperationQueue()
|
||||
private let emitQueue = dispatch_queue_create(
|
||||
"engineEmitQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||
@@ -70,6 +69,8 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
var connected:Bool {
|
||||
return self._connected
|
||||
}
|
||||
|
||||
weak var client:SocketEngineClient?
|
||||
var cookies:[NSHTTPCookie]?
|
||||
var pingInterval:Int?
|
||||
var polling:Bool {
|
||||
@@ -97,15 +98,11 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
self.pingTimer?.invalidate()
|
||||
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")
|
||||
}
|
||||
self.write("", withType: PacketType.CLOSE, withData: nil)
|
||||
self.ws?.disconnect()
|
||||
|
||||
if fast || self.polling {
|
||||
self.client?.didForceClose("Disconnect")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,11 +123,15 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
|
||||
private func createURLs(params:[String: AnyObject]?) -> (String, String) {
|
||||
var url = "\(self.client.socketURL)/socket.io/?transport="
|
||||
if self.client == nil {
|
||||
return ("", "")
|
||||
}
|
||||
|
||||
var url = "\(self.client!.socketURL)/socket.io/?transport="
|
||||
var urlPolling:String
|
||||
var urlWebSocket:String
|
||||
|
||||
if self.client.secure {
|
||||
if self.client!.secure {
|
||||
urlPolling = "https://" + url + "polling"
|
||||
urlWebSocket = "wss://" + url + "websocket"
|
||||
} else {
|
||||
@@ -164,17 +165,23 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
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)
|
||||
if self.waitingForPoll {
|
||||
NSLog("Outstanding poll when switched to websockets," +
|
||||
"we'll probably disconnect soon. You should report this.")
|
||||
}
|
||||
|
||||
self.sendWebSocketMessage("", withType: PacketType.UPGRADE, datas: nil)
|
||||
self._websocket = true
|
||||
self._polling = false
|
||||
self.fastUpgrade = false
|
||||
self.probing = false
|
||||
self.flushProbeWait()
|
||||
}
|
||||
|
||||
@@ -203,6 +210,8 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
} else if err != nil {
|
||||
if self!.polling {
|
||||
self?.handlePollingFailed(err.localizedDescription)
|
||||
} else {
|
||||
NSLog(err.localizedDescription)
|
||||
}
|
||||
|
||||
return
|
||||
@@ -218,18 +227,17 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
|
||||
self?.waitingForPoll = false
|
||||
|
||||
if self!.fastUpgrade {
|
||||
self?.doFastUpgrade()
|
||||
return
|
||||
} else if !self!.closed && !self!.websocket {
|
||||
} else if !self!.closed && self!.polling {
|
||||
self?.doPoll()
|
||||
}
|
||||
}.resume()
|
||||
}
|
||||
|
||||
private func flushProbeWait() {
|
||||
// println("flushing probe wait")
|
||||
// NSLog("flushing probe wait")
|
||||
dispatch_async(self.emitQueue) {[weak self] in
|
||||
if self == nil {
|
||||
return
|
||||
@@ -240,6 +248,10 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
|
||||
self?.probeWait.removeAll(keepCapacity: false)
|
||||
|
||||
if self?.postWait.count != 0 {
|
||||
self?.flushWaitingForPostToWebSocket()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -269,24 +281,31 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
|
||||
allowLossyConversion: false)!
|
||||
|
||||
// NSLog("posting: \(postStr)")
|
||||
req.HTTPBody = postData
|
||||
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
|
||||
|
||||
self.waitingForPost = true
|
||||
|
||||
// NSLog("posting: \(postStr)")
|
||||
// NSLog("Posting with WS status of: \(self.websocket)")
|
||||
|
||||
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
||||
if self == nil {
|
||||
return
|
||||
} else if err != nil && self!.polling {
|
||||
self?.handlePollingFailed(err.localizedDescription)
|
||||
return
|
||||
} else if err != nil {
|
||||
NSLog(err.localizedDescription)
|
||||
return
|
||||
}
|
||||
|
||||
self?.waitingForPost = false
|
||||
dispatch_async(self!.emitQueue) {
|
||||
self?.flushWaitingForPost()
|
||||
self?.doPoll()
|
||||
return
|
||||
if !self!.fastUpgrade {
|
||||
self?.flushWaitingForPost()
|
||||
self?.doPoll()
|
||||
}
|
||||
}}.resume()
|
||||
}
|
||||
|
||||
@@ -308,10 +327,14 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
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)
|
||||
if self.client == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if !self.closed && !self.client!.reconnecting {
|
||||
self.client?.pollingDidFail(reason)
|
||||
} else if !self.client!.reconnecting {
|
||||
self.client?.didForceClose(reason)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -401,8 +424,12 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
|
||||
private func parseEngineData(data:NSData) {
|
||||
dispatch_async(self.client.handleQueue) {[weak self] in
|
||||
self?.client.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
|
||||
if self.client == nil {
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(self.client!.handleQueue) {[weak self] in
|
||||
self?.client?.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -426,8 +453,13 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
if let data = NSData(base64EncodedString: message,
|
||||
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) {
|
||||
// println("sending \(data)")
|
||||
dispatch_async(self.client.handleQueue) {[weak self] in
|
||||
self?.client.parseBinaryData(data)
|
||||
|
||||
if self.client == nil {
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(self.client!.handleQueue) {[weak self] in
|
||||
self?.client?.parseBinaryData(data)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -442,6 +474,8 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
self.upgradeTransport()
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
} else if type == PacketType.OPEN.rawValue {
|
||||
var err:NSError?
|
||||
|
||||
@@ -477,8 +511,12 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
|
||||
return
|
||||
} else if type == PacketType.CLOSE.rawValue {
|
||||
if self.client == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if self.polling {
|
||||
self.client.didForceClose("Disconnect")
|
||||
self.client!.didForceClose("Disconnect")
|
||||
}
|
||||
|
||||
return
|
||||
@@ -490,8 +528,12 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
// Remove message type
|
||||
message.removeAtIndex(message.startIndex)
|
||||
|
||||
dispatch_async(self.client.handleQueue) {[weak self] in
|
||||
self?.client.parseSocketMessage(message)
|
||||
if self.client == nil {
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(self.client!.handleQueue) {[weak self] in
|
||||
self?.client?.parseSocketMessage(message)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -512,13 +554,11 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
|
||||
func sendPing() {
|
||||
if self.websocket {
|
||||
self.sendWebSocketMessage("", withType: PacketType.PING)
|
||||
} else {
|
||||
self.sendPollMessage("", withType: PacketType.PING)
|
||||
}
|
||||
self.write("", withType: PacketType.PING, withData: nil)
|
||||
}
|
||||
|
||||
/// Send polling message.
|
||||
/// Only call on emitQueue
|
||||
private func sendPollMessage(var msg:String, withType type:PacketType,
|
||||
datas:ContiguousArray<NSData>? = nil) {
|
||||
// println("Sending poll: \(msg) as type: \(type.rawValue)")
|
||||
@@ -540,6 +580,8 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
/// Send message on WebSockets
|
||||
/// Only call on emitQueue
|
||||
private func sendWebSocketMessage(str:String, withType type:PacketType,
|
||||
datas:ContiguousArray<NSData>? = nil) {
|
||||
// println("Sending ws: \(str) as type: \(type.rawValue)")
|
||||
@@ -571,9 +613,10 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
|
||||
private func upgradeTransport() {
|
||||
if self.websocketConnected {
|
||||
// NSLog("Doing fast upgrade")
|
||||
// Do a fast upgrade
|
||||
// At this point, we should not send anymore polling messages-
|
||||
self.fastUpgrade = true
|
||||
self.probing = false
|
||||
self.sendPollMessage("", withType: PacketType.NOOP)
|
||||
}
|
||||
}
|
||||
@@ -613,13 +656,18 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
||||
self.websocketConnected = false
|
||||
self.probing = false
|
||||
|
||||
if self.closed {
|
||||
self.client?.didForceClose("Disconnect")
|
||||
return
|
||||
}
|
||||
|
||||
if self.websocket {
|
||||
self.pingTimer?.invalidate()
|
||||
self._connected = false
|
||||
self._websocket = false
|
||||
|
||||
let reason = error?.localizedDescription
|
||||
self.client.webSocketDidCloseWithCode(1,
|
||||
self.client?.webSocketDidCloseWithCode(1,
|
||||
reason: reason == nil ? "Socket Disconnected" : reason!)
|
||||
} else {
|
||||
self.flushProbeWait()
|
||||
|
||||
@@ -25,9 +25,7 @@
|
||||
import Foundation
|
||||
|
||||
public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
let reconnectAttempts:Int!
|
||||
private lazy var params = [String: AnyObject]()
|
||||
private var ackHandlers = ContiguousArray<SocketAckHandler>()
|
||||
private var anyHandler:((SocketAnyEvent) -> Void)?
|
||||
private var _closed = false
|
||||
private var _connected = false
|
||||
@@ -42,14 +40,15 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
private var _reconnecting = false
|
||||
private var reconnectTimer:NSTimer?
|
||||
|
||||
let reconnectAttempts:Int!
|
||||
var ackHandlers = SocketAckMap()
|
||||
var currentAck = -1
|
||||
var waitingData = ContiguousArray<SocketPacket>()
|
||||
|
||||
public let socketURL:String
|
||||
public let handleQueue = dispatch_queue_create("handleQueue".cStringUsingEncoding(NSUTF8StringEncoding),
|
||||
DISPATCH_QUEUE_SERIAL)
|
||||
public let emitQueue = dispatch_queue_create("emitQueue".cStringUsingEncoding(NSUTF8StringEncoding),
|
||||
DISPATCH_QUEUE_SERIAL)
|
||||
public let handleAckQueue = dispatch_queue_create("handleAckQueue", DISPATCH_QUEUE_SERIAL)
|
||||
public let handleQueue = dispatch_queue_create("handleQueue", DISPATCH_QUEUE_SERIAL)
|
||||
public let emitQueue = dispatch_queue_create("emitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
public var closed:Bool {
|
||||
return self._closed
|
||||
}
|
||||
@@ -89,6 +88,26 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
|
||||
// Set options
|
||||
if opts != nil {
|
||||
if let cookies = opts!["cookies"] as? [NSHTTPCookie] {
|
||||
self.cookies = cookies
|
||||
}
|
||||
|
||||
if let polling = opts!["forcePolling"] as? Bool {
|
||||
self.forcePolling = polling
|
||||
}
|
||||
|
||||
if let ws = opts!["forceWebsockets"] as? Bool {
|
||||
self.forceWebsockets = ws
|
||||
}
|
||||
|
||||
if var nsp = opts!["nsp"] as? String {
|
||||
if nsp != "/" && nsp.hasPrefix("/") {
|
||||
nsp.removeAtIndex(nsp.startIndex)
|
||||
}
|
||||
|
||||
self.nsp = nsp
|
||||
}
|
||||
|
||||
if let reconnects = opts!["reconnects"] as? Bool {
|
||||
self.reconnects = reconnects
|
||||
}
|
||||
@@ -102,26 +121,6 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
if let reconnectWait = opts!["reconnectWait"] as? Int {
|
||||
self.reconnectWait = abs(reconnectWait)
|
||||
}
|
||||
|
||||
if var nsp = opts!["nsp"] as? String {
|
||||
if nsp != "/" && nsp.hasPrefix("/") {
|
||||
nsp.removeAtIndex(nsp.startIndex)
|
||||
}
|
||||
|
||||
self.nsp = nsp
|
||||
}
|
||||
|
||||
if let polling = opts!["forcePolling"] as? Bool {
|
||||
self.forcePolling = polling
|
||||
}
|
||||
|
||||
if let ws = opts!["forceWebsockets"] as? Bool {
|
||||
self.forceWebsockets = ws
|
||||
}
|
||||
|
||||
if let cookies = opts!["cookies"] as? [NSHTTPCookie] {
|
||||
self.cookies = cookies
|
||||
}
|
||||
} else {
|
||||
self.reconnectAttempts = -1
|
||||
}
|
||||
@@ -190,6 +189,30 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
self.engine?.open(opts: params)
|
||||
}
|
||||
|
||||
private func createOnAck(event:String, items:[AnyObject]) -> OnAckCallback {
|
||||
return {[weak self, ack = ++self.currentAck] timeout, callback in
|
||||
if self == nil {
|
||||
return
|
||||
}
|
||||
|
||||
self?.ackHandlers.addAck(ack, callback)
|
||||
|
||||
dispatch_async(self!.emitQueue) {
|
||||
self?._emit(event, items, ack: ack)
|
||||
return
|
||||
}
|
||||
|
||||
if timeout != 0 {
|
||||
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
|
||||
|
||||
dispatch_after(time, dispatch_get_main_queue()) {
|
||||
self?.ackHandlers.timeoutAck(ack)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func didConnect() {
|
||||
self._closed = false
|
||||
self._connected = true
|
||||
@@ -219,6 +242,13 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
self.handleEvent("disconnect", data: [reason], isInternalMessage: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Same as close
|
||||
*/
|
||||
public func disconnect(#fast:Bool) {
|
||||
self.close(fast: fast)
|
||||
}
|
||||
|
||||
/**
|
||||
Send a message to the server
|
||||
*/
|
||||
@@ -251,43 +281,23 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
|
||||
an ack.
|
||||
*/
|
||||
public func emitWithAck(event:String, _ items:AnyObject...) -> SocketAckHandler {
|
||||
public func emitWithAck(event:String, _ items:AnyObject...) -> OnAckCallback {
|
||||
if !self.connected {
|
||||
return SocketAckHandler(event: "fail", socket: self)
|
||||
return createOnAck(event, items: items)
|
||||
}
|
||||
|
||||
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
|
||||
return self.createOnAck(event, items: items)
|
||||
}
|
||||
|
||||
/**
|
||||
Same as emitWithAck, but for Objective-C
|
||||
*/
|
||||
public func emitWithAckObjc(event:String, withItems items:[AnyObject]) -> SocketAckHandler {
|
||||
public func emitWithAckObjc(event:String, withItems items:[AnyObject]) -> OnAckCallback {
|
||||
if !self.connected {
|
||||
return SocketAckHandler(event: "fail", socket: self)
|
||||
return self.createOnAck(event, items: items)
|
||||
}
|
||||
|
||||
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
|
||||
return self.createOnAck(event, items: items)
|
||||
}
|
||||
|
||||
private func _emit(event:String, _ args:[AnyObject], ack:Int? = nil) {
|
||||
@@ -331,21 +341,15 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
|
||||
// Called when the socket gets an ack for something it sent
|
||||
func handleAck(ack:Int, data:AnyObject?) {
|
||||
self.ackHandlers = self.ackHandlers.filter {handler in
|
||||
if handler.ackNum != ack {
|
||||
return true
|
||||
} else {
|
||||
if data is NSArray {
|
||||
handler.executeAck(data as? NSArray)
|
||||
} else if data != nil {
|
||||
handler.executeAck([data!])
|
||||
} else {
|
||||
handler.executeAck(nil)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
var ackData:[AnyObject]?
|
||||
|
||||
if data is NSArray {
|
||||
ackData = data as? NSArray
|
||||
} else if data != nil {
|
||||
ackData = [data!]
|
||||
}
|
||||
|
||||
self.ackHandlers.executeAck(ack, items: ackData)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -428,10 +432,6 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
||||
}
|
||||
}
|
||||
|
||||
func removeAck(ack:SocketAckHandler) {
|
||||
self.ackHandlers = self.ackHandlers.filter {$0 === ack ? false : true}
|
||||
}
|
||||
|
||||
// We lost connection and should attempt to reestablish
|
||||
func tryReconnect() {
|
||||
if self.reconnectAttempts != -1 && self.currentReconnectAttempt + 1 > self.reconnectAttempts {
|
||||
|
||||
+48
-48
@@ -24,7 +24,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
enum SocketPacketType: Int {
|
||||
enum SocketPacketType:Int {
|
||||
case CONNECT = 0
|
||||
case DISCONNECT = 1
|
||||
case EVENT = 2
|
||||
@@ -90,68 +90,68 @@ class SocketPacket {
|
||||
}
|
||||
|
||||
func createMessageForEvent(event:String) -> String {
|
||||
var message:String
|
||||
var jsonSendError:NSError?
|
||||
var message:String
|
||||
var jsonSendError:NSError?
|
||||
|
||||
if self.binary.count == 0 {
|
||||
self.type = SocketPacketType.EVENT
|
||||
|
||||
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)\""
|
||||
}
|
||||
if self.nsp == "/" {
|
||||
if self.id == nil {
|
||||
message = "2[\"\(event)\""
|
||||
} else {
|
||||
if self.id == nil {
|
||||
message = "2/\(self.nsp),[\"\(event)\""
|
||||
} else {
|
||||
message = "2/\(self.nsp),\(self.id!)[\"\(event)\""
|
||||
}
|
||||
message = "2\(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)\""
|
||||
}
|
||||
if self.id == nil {
|
||||
message = "2/\(self.nsp),[\"\(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)\""
|
||||
}
|
||||
message = "2/\(self.nsp),\(self.id!)[\"\(event)\""
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.type = SocketPacketType.BINARY_EVENT
|
||||
|
||||
return self.completeMessage(message)
|
||||
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
|
||||
var msg:String
|
||||
|
||||
if self.binary.count == 0 {
|
||||
self.type = SocketPacketType.ACK
|
||||
|
||||
if self.binary.count == 0 {
|
||||
self.type = SocketPacketType.ACK
|
||||
|
||||
if nsp == "/" {
|
||||
msg = "3\(self.id!)["
|
||||
} else {
|
||||
msg = "3/\(self.nsp),\(self.id!)["
|
||||
}
|
||||
if nsp == "/" {
|
||||
msg = "3\(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!)["
|
||||
}
|
||||
msg = "3/\(self.nsp),\(self.id!)["
|
||||
}
|
||||
} else {
|
||||
self.type = SocketPacketType.BINARY_ACK
|
||||
|
||||
return self.completeMessage(msg, ack: true)
|
||||
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 {
|
||||
|
||||
Reference in new issue
Block a user