Compare commits

...
38 Commits
Author SHA1 Message Date
Erik 1b4b571be6 bump version 2016-04-11 18:58:02 -04:00
Erik Little c9f653ef2c Merge pull request #344 from socketio/development
Development
2016-04-11 18:55:27 -04:00
Erik 3073130598 change to how server gives id 2016-04-11 18:51:22 -04:00
Erik ed3d49001f bump websocket version 2016-04-10 13:59:21 -04:00
Erik 4ee196c5fb add default value to namespace in socketparsable 2016-04-04 11:28:20 -04:00
Erik baca9fc8da small refactors 2016-03-31 21:31:24 -04:00
Erik 1a5ac74984 Merge branch 'master' into development
* master:
  set targetted device family to 3
  use 7.3 image
2016-03-25 17:02:52 -04:00
Erik Little 6c779e84d2 Merge pull request #335 from craigkj312/master
actual fix for carthage
2016-03-25 17:01:53 -04:00
Kyle Craig 293d71bf97 set targetted device family to 3 2016-03-25 15:54:57 -05:00
Erik 2f1f77141e add test for objc api 2016-03-25 10:00:14 -04:00
Erik d4c01183ab style 2016-03-25 09:48:04 -04:00
Erik 5d81377e0a use 7.3 image 2016-03-24 14:46:32 -04:00
Erik 8f8d5acdba use 7.3 image 2016-03-24 14:17:49 -04:00
Erik a0167ae213 remove deprecated methods 2016-03-23 13:39:22 -04:00
Erik 4f5837afa7 don't need objc on this method anymore 2016-03-22 10:15:09 -04:00
Erik 718caba9d9 remove nstimer 2016-03-22 09:56:56 -04:00
Erik Little 2919d4a5ce Merge pull request #330 from socketio/development
Development
2016-03-22 09:06:13 -04:00
Erik a53b7167b6 update version and readme 2016-03-22 09:05:57 -04:00
Erik 6c6b4f32c9 Update for swift 2.2 2016-03-22 09:00:27 -04:00
Erik 3a842469ec fix log placement 2016-03-16 13:13:22 -04:00
Erik 596a499041 work on fixing reconnect() 2016-03-11 13:41:09 -05:00
Erik 76a572e735 refactor reconnect 2016-03-11 13:03:40 -05:00
Erik 6da9463c8d whitespace 2016-03-03 10:11:08 -05:00
Erik 2f7a5405b0 add check for fast upgrade 2016-03-03 09:59:33 -05:00
Erik 62131ef904 make sure we don't handle poll messages if we aren't polling 2016-03-03 09:57:39 -05:00
Erik 5976ef1752 bump websocket version 2016-02-27 19:43:21 -05:00
Erik 16e0bf6319 bump version 2016-02-25 19:13:08 -05:00
Erik Little 11c0ac249b Merge pull request #317 from jtjacka/master
fix timeoutAfter handler always close connection
2016-02-25 19:11:33 -05:00
jtjacka 1e96d7982d fix timeoutAfter handler always close connection 2016-02-25 16:06:08 -08:00
Erik 2f4c942dcf use connect/disconnect for engine 2016-02-23 10:33:14 -05:00
Erik 70283acc1f add messages to deprecated methods 2016-02-17 14:27:48 -05:00
Erik e16914f7d6 remove unused param 2016-02-17 14:15:15 -05:00
Erik c795f9fb25 refactor socketpacket 2016-02-17 14:09:05 -05:00
Erik 12f9207d8a rename waitingData to waitingPackets 2016-02-16 17:03:00 -05:00
Erik 0bf27b8c49 bump version 2016-02-16 14:28:18 -05:00
Erik 6ac96f8d91 modify test 2016-02-16 14:27:18 -05:00
Erik f7397155b6 add test cases 2016-02-16 14:26:21 -05:00
Erik 70d59ea9d4 fix quotes in strings 2016-02-16 14:21:10 -05:00
25 changed files with 398 additions and 385 deletions

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
language: objective-c
xcode_project: Socket.IO-Client-Swift.xcodeproj # path to your xcodeproj folder
xcode_scheme: SocketIO-iOS
osx_image: xcode7
osx_image: xcode7.3
before_install:
- cd Socket.IO-Test-Server/
- npm install
+6 -4
View File
@@ -55,7 +55,9 @@ SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:url options:@
- Can be used from Objective-C
##Installation
Requires Swift 2/Xcode 7
Requires Swift 2.2/Xcode 7.3
If you need Swift 2.1/Xcode 7.2 use v5.5.0 (Pre-Swift 2.2 support is no longer maintained)
If you need Swift 1.2/Xcode 6.3/4 use v2.4.5 (Pre-Swift 2 support is no longer maintained)
@@ -86,7 +88,7 @@ Carthage
-----------------
Add this line to your `Cartfile`:
```
github "socketio/socket.io-client-swift" ~> 5.4.0 # Or latest version
github "socketio/socket.io-client-swift" ~> 6.1.0 # Or latest version
```
Run `carthage update --platform ios,macosx`.
@@ -100,7 +102,7 @@ source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'Socket.IO-Client-Swift', '~> 5.4.0' # Or latest version
pod 'Socket.IO-Client-Swift', '~> 6.1.0' # Or latest version
```
Install pods:
@@ -128,7 +130,7 @@ CocoaSeeds
Add this line to your `Seedfile`:
```
github "socketio/socket.io-client-swift", "v5.4.0", :files => "Source/*.swift" # Or latest version
github "socketio/socket.io-client-swift", "v6.1.0", :files => "Source/*.swift" # Or latest version
```
Run `seed install`.
+2 -2
View File
@@ -1,7 +1,7 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.module_name = "SocketIOClientSwift"
s.version = "5.4.0"
s.version = "6.1.0"
s.summary = "Socket.IO-client for iOS and OS X"
s.description = <<-DESC
Socket.IO-client for iOS and OS X.
@@ -14,7 +14,7 @@ Pod::Spec.new do |s|
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.tvos.deployment_target = '9.0'
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v5.4.0' }
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v6.1.0' }
s.source_files = "Source/**/*.swift"
s.requires_arc = true
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
@@ -116,6 +116,7 @@
7420CB791C49629E00956AA4 /* SocketEnginePollable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */; };
7420CB7A1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */; };
7420CB7B1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */; };
742D150C1CA5794B00BD987D /* SocketObjectiveCTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 742D150B1CA5794B00BD987D /* SocketObjectiveCTest.m */; };
74321DCB1C2D939A00CF6F43 /* SocketAckManagerTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74321DC91C2D939A00CF6F43 /* SocketAckManagerTest.swift */; };
74321DCC1C2D939A00CF6F43 /* SocketParserTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74321DCA1C2D939A00CF6F43 /* SocketParserTest.swift */; };
7471CCEA1C39926300364B59 /* SocketClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketClientSpec.swift */; };
@@ -187,6 +188,7 @@
74171E621C10CD240062D398 /* WebSocket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = Source/WebSocket.swift; sourceTree = "<group>"; };
741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketEngineTest.swift; sourceTree = "<group>"; };
7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketEnginePollable.swift; path = Source/SocketEnginePollable.swift; sourceTree = "<group>"; };
742D150B1CA5794B00BD987D /* SocketObjectiveCTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SocketObjectiveCTest.m; sourceTree = "<group>"; };
74321DC91C2D939A00CF6F43 /* SocketAckManagerTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SocketAckManagerTest.swift; sourceTree = "<group>"; };
74321DCA1C2D939A00CF6F43 /* SocketParserTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SocketParserTest.swift; sourceTree = "<group>"; };
7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketNamespacePacketTest.swift; sourceTree = "<group>"; };
@@ -326,6 +328,7 @@
74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */,
741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */,
7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */,
742D150B1CA5794B00BD987D /* SocketObjectiveCTest.m */,
74321DCA1C2D939A00CF6F43 /* SocketParserTest.swift */,
7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */,
572EF2471B51F18A00EEBB58 /* Supporting Files */,
@@ -513,7 +516,7 @@
572EF20E1B51F12F00EEBB58 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0710;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 0720;
TargetAttributes = {
572EF2181B51F16C00EEBB58 = {
@@ -687,6 +690,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
742D150C1CA5794B00BD987D /* SocketObjectiveCTest.m in Sources */,
74321DCB1C2D939A00CF6F43 /* SocketAckManagerTest.swift in Sources */,
74321DCC1C2D939A00CF6F43 /* SocketParserTest.swift in Sources */,
7472C6601BCAC46E003CA70D /* SocketSideEffectTest.swift in Sources */,
@@ -1169,6 +1173,7 @@
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
@@ -1269,7 +1274,7 @@
SDKROOT = appletvos;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
TARGETED_DEVICE_FAMILY = "1,2";
TARGETED_DEVICE_FAMILY = 3;
TVOS_DEPLOYMENT_TARGET = 9.0;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
@@ -1320,7 +1325,7 @@
PRODUCT_NAME = SocketIO;
SDKROOT = appletvos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = "1,2";
TARGETED_DEVICE_FAMILY = 3;
TVOS_DEPLOYMENT_TARGET = 9.0;
VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic";
@@ -37,6 +37,14 @@ class SocketBasicPacketTest: XCTestCase {
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testStringEmitWithQuotes() {
let expectedSendString = "2[\"test\",\"\\\"he\\\"llo world\\\"\"]"
let sendData = ["test", "\"he\"llo world\""]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testJSONEmit() {
let expectedSendString = "2[\"test\",{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
let sendData = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
+45
View File
@@ -0,0 +1,45 @@
//
// SocketObjectiveCTest.m
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/25/16.
//
// Merely tests whether the Objective-C api breaks
//
#import <XCTest/XCTest.h>
@import SocketIOClientSwift;
@interface SocketObjectiveCTest : XCTestCase
@property SocketIOClient* socket;
@end
@implementation SocketObjectiveCTest
- (void)setUp {
[super setUp];
NSURL* url = [[NSURL alloc] initWithString:@"http://localhost"];
self.socket = [[SocketIOClient alloc] initWithSocketURL:url options:nil];
}
- (void)testOnSyntax {
[self.socket on:@"someCallback" callback:^(NSArray* data, SocketAckEmitter* ack) {
[ack with:@[@1]];
}];
}
- (void)testEmitSyntax {
[self.socket emit:@"testEmit" withItems:@[@YES]];
}
- (void)testEmitWithAckSyntax {
[self.socket emitWithAck:@"testAckEmit" withItems:@[@YES]];
}
- (void)testOffSyntax {
[self.socket off:@"test"];
}
@end
+7 -1
View File
@@ -25,6 +25,7 @@ class SocketParserTest: XCTestCase {
"0/swift": ("/swift", [], [], -1),
"1/swift": ("/swift", [], [], -1),
"4\"ERROR\"": ("/", ["ERROR"], [], -1),
"4{\"test\":2}": ("/", [["test": 2]], [], -1),
"41": ("/", [1], [], -1)]
func testDisconnect() {
@@ -87,6 +88,11 @@ class SocketParserTest: XCTestCase {
validateParseResult(message)
}
func testErrorTypeDictionary() {
let message = "4{\"test\":2}"
validateParseResult(message)
}
func testErrorTypeInt() {
let message = "41"
validateParseResult(message)
@@ -113,7 +119,7 @@ class SocketParserTest: XCTestCase {
func validateParseResult(message: String) {
let validValues = SocketParserTest.packetTypes[message]!
let packet = testSocket.parseString(message)
let type = message.substringWithRange(Range<String.Index>(start: message.startIndex, end: message.startIndex.advancedBy(1)))
let type = message.substringWithRange(Range<String.Index>(message.startIndex..<message.startIndex.advancedBy(1)))
if case let .Right(packet) = packet {
XCTAssertEqual(packet.type, SocketPacket.PacketType(rawValue: Int(type) ?? -1)!)
XCTAssertEqual(packet.nsp, validValues.0)
@@ -70,6 +70,17 @@ class SocketSideEffectTest: XCTestCase {
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleStringEventWithQuotes() {
let expectation = expectationWithDescription("handled event")
socket.on("test") {data, ack in
XCTAssertEqual(data[0] as? String, "\"hello world\"")
expectation.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"\\\"hello world\\\"\"]")
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleOnceEvent() {
let expectation = expectationWithDescription("handled event")
socket.once("test") {data, ack in
+1 -1
View File
@@ -24,7 +24,7 @@
import Foundation
public final class SocketAckEmitter: NSObject {
public final class SocketAckEmitter : NSObject {
let socket: SocketIOClient
let ackNum: Int
+1 -1
View File
@@ -24,7 +24,7 @@
import Foundation
private struct SocketAck: Hashable, Equatable {
private struct SocketAck : Hashable, Equatable {
let ack: Int
var callback: AckCallback!
var hashValue: Int {
+1 -1
View File
@@ -24,7 +24,7 @@
import Foundation
public final class SocketAnyEvent: NSObject {
public final class SocketAnyEvent : NSObject {
public let event: String
public let items: NSArray?
override public var description: String {
+2 -2
View File
@@ -22,9 +22,9 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
protocol SocketClientSpec: class {
protocol SocketClientSpec : class {
var nsp: String { get set }
var waitingData: [SocketPacket] { get set }
var waitingPackets: [SocketPacket] { get set }
func didConnect()
func didDisconnect(reason: String)
+81 -95
View File
@@ -24,7 +24,7 @@
import Foundation
public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWebsocket {
public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWebsocket {
public let emitQueue = dispatch_queue_create("com.socketio.engineEmitQueue", DISPATCH_QUEUE_SERIAL)
public let handleQueue = dispatch_queue_create("com.socketio.engineHandleQueue", DISPATCH_QUEUE_SERIAL)
public let parseQueue = dispatch_queue_create("com.socketio.engineParseQueue", DISPATCH_QUEUE_SERIAL)
@@ -47,7 +47,6 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
public private(set) var forcePolling = false
public private(set) var forceWebsockets = false
public private(set) var invalidated = false
public private(set) var pingTimer: NSTimer?
public private(set) var polling = true
public private(set) var probing = false
public private(set) var session: NSURLSession?
@@ -123,18 +122,6 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? [])
}
@available(*, deprecated=5.3)
public convenience init(client: SocketEngineClient, urlString: String, options: Set<SocketIOClientOption>) {
guard let url = NSURL(string: urlString) else { fatalError("Incorrect url") }
self.init(client: client, url: url, options: options)
}
@available(*, deprecated=5.3)
public convenience init(client: SocketEngineClient, urlString: String, options: NSDictionary?) {
guard let url = NSURL(string: urlString) else { fatalError("Incorrect url") }
self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Engine is being released", type: logType)
closed = true
@@ -184,34 +171,40 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
return false
}
}
public func close(reason: String) {
func postSendClose(data: NSData?, _ res: NSURLResponse?, _ err: NSError?) {
sid = ""
closed = true
invalidated = true
connected = false
pingTimer?.invalidate()
ws?.disconnect()
stopPolling()
client?.engineDidClose(reason)
/// Starts the connection to the server
public func connect() {
if connected {
DefaultSocketLogger.Logger.error("Engine tried opening while connected. Assuming this was a reconnect", type: logType)
disconnect("reconnect")
}
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
DefaultSocketLogger.Logger.log("Starting engine", type: logType)
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
if websocket {
sendWebSocketMessage("", withType: .Close, withData: [])
postSendClose(nil, nil, nil)
} else {
// We need to take special care when we're polling that we send it ASAP
// Also make sure we're on the emitQueue since we're touching postWait
dispatch_sync(emitQueue) {
self.postWait.append(String(SocketEnginePacketType.Close.rawValue))
let req = self.createRequestForPostWithPostWait()
self.doRequest(req, withCallback: postSendClose)
resetEngine()
if forceWebsockets {
polling = false
websocket = true
createWebsocketAndConnect()
return
}
let reqPolling = NSMutableURLRequest(URL: urlPolling)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doLongPoll(reqPolling)
}
private func createURLs() -> (NSURL, NSURL) {
@@ -275,7 +268,39 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
public func didError(error: String) {
DefaultSocketLogger.Logger.error(error, type: logType)
client?.engineDidError(error)
close(error)
disconnect(error)
}
public func disconnect(reason: String) {
func postSendClose(data: NSData?, _ res: NSURLResponse?, _ err: NSError?) {
sid = ""
closed = true
invalidated = true
connected = false
ws?.disconnect()
stopPolling()
client?.engineDidClose(reason)
}
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
if closed {
return postSendClose(nil, nil, nil)
}
if websocket {
sendWebSocketMessage("", withType: .Close, withData: [])
postSendClose(nil, nil, nil)
} else {
// We need to take special care when we're polling that we send it ASAP
// Also make sure we're on the emitQueue since we're touching postWait
dispatch_sync(emitQueue) {
self.postWait.append(String(SocketEnginePacketType.Close.rawValue))
let req = self.createRequestForPostWithPostWait()
self.doRequest(req, withCallback: postSendClose)
}
}
}
public func doFastUpgrade() {
@@ -358,8 +383,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
createWebsocketAndConnect()
}
startPingTimer()
sendPing()
if !forceWebsockets {
doPoll()
@@ -381,41 +405,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
upgradeTransport()
}
}
public func open() {
if connected {
DefaultSocketLogger.Logger.error("Engine tried opening while connected. Assuming this was a reconnect", type: logType)
close("reconnect")
}
DefaultSocketLogger.Logger.log("Starting engine", type: logType)
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
resetEngine()
if forceWebsockets {
polling = false
websocket = true
createWebsocketAndConnect()
return
}
let reqPolling = NSMutableURLRequest(URL: urlPolling)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doLongPoll(reqPolling)
}
public func parseEngineData(data: NSData) {
DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data)
client?.parseEngineBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
@@ -457,6 +447,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
}
// Puts the engine back in its default state
private func resetEngine() {
closed = false
connected = false
@@ -473,31 +464,29 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
websocket = false
}
@objc private func sendPing() {
private func sendPing() {
if !connected {
return
}
//Server is not responding
if pongsMissed > pongsMissedMax {
pingTimer?.invalidate()
client?.engineDidClose("Ping timeout")
return
}
pongsMissed += 1
write("", withType: .Ping, withData: [])
}
// Starts the ping timer
private func startPingTimer() {
if let pingInterval = pingInterval {
pingTimer?.invalidate()
pingTimer = nil
dispatch_async(dispatch_get_main_queue()) {
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self,
selector: Selector("sendPing"), userInfo: nil, repeats: true)
pongsMissed += 1
write("", withType: .Ping, withData: [])
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(pingInterval * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) {[weak self] in
self?.sendPing()
}
}
}
// Moves from long-polling to websockets
private func upgradeTransport() {
if ws?.isConnected ?? false {
DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: logType)
@@ -508,9 +497,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
}
/**
Write a message, independent of transport.
*/
/// Write a message, independent of transport.
public func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData]) {
dispatch_async(emitQueue) {
guard self.connected else { return }
@@ -550,7 +537,6 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
if websocket {
pingTimer?.invalidate()
connected = false
websocket = false
+1 -1
View File
@@ -25,6 +25,6 @@
import Foundation
@objc public enum SocketEnginePacketType: Int {
@objc public enum SocketEnginePacketType : Int {
case Open, Close, Ping, Pong, Message, Upgrade, Noop
}
+11 -11
View File
@@ -25,7 +25,7 @@
import Foundation
/// Protocol that is used to implement socket.io polling support
public protocol SocketEnginePollable: SocketEngineSpec {
public protocol SocketEnginePollable : SocketEngineSpec {
var invalidated: Bool { get }
/// Holds strings waiting to be sent over polling.
/// You shouldn't need to mess with this.
@@ -100,19 +100,19 @@ extension SocketEnginePollable {
}
func doRequest(req: NSURLRequest, withCallback callback: (NSData?, NSURLResponse?, NSError?) -> Void) {
if !polling || closed || invalidated {
DefaultSocketLogger.Logger.error("Tried to do polling request when not supposed to", type: "SocketEnginePolling")
return
}
DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling")
session?.dataTaskWithRequest(req, completionHandler: callback).resume()
if !polling || closed || invalidated || fastUpgrade {
DefaultSocketLogger.Logger.error("Tried to do polling request when not supposed to", type: "SocketEnginePolling")
return
}
DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling")
session?.dataTaskWithRequest(req, completionHandler: callback).resume()
}
func doLongPoll(req: NSURLRequest) {
doRequest(req) {[weak self] data, res, err in
guard let this = self else { return }
guard let this = self where this.polling else { return }
if err != nil || data == nil {
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
@@ -123,7 +123,7 @@ extension SocketEnginePollable {
return
}
DefaultSocketLogger.Logger.log("Got polling response", type: "SocketEnginePolling")
if let str = String(data: data!, encoding: NSUTF8StringEncoding) {
+2 -3
View File
@@ -37,7 +37,6 @@ import Foundation
var forcePolling: Bool { get }
var forceWebsockets: Bool { get }
var parseQueue: dispatch_queue_t! { get }
var pingTimer: NSTimer? { get }
var polling: Bool { get }
var probing: Bool { get }
var emitQueue: dispatch_queue_t! { get }
@@ -50,11 +49,11 @@ import Foundation
init(client: SocketEngineClient, url: NSURL, options: NSDictionary?)
func close(reason: String)
func connect()
func didError(error: String)
func disconnect(reason: String)
func doFastUpgrade()
func flushWaitingForPostToWebSocket()
func open()
func parseEngineData(data: NSData)
func parseEngineMessage(message: String, fromPolling: Bool)
func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData])
+1 -1
View File
@@ -26,7 +26,7 @@
import Foundation
/// Protocol that is used to implement socket.io WebSocket support
public protocol SocketEngineWebsocket: SocketEngineSpec, WebSocketDelegate {
public protocol SocketEngineWebsocket : SocketEngineSpec, WebSocketDelegate {
var ws: WebSocket? { get }
func sendWebSocketMessage(str: String, withType type: SocketEnginePacketType, withData datas: [NSData])
+82 -146
View File
@@ -24,11 +24,21 @@
import Foundation
public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable {
public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable {
public let socketURL: NSURL
public private(set) var engine: SocketEngineSpec?
public private(set) var status = SocketIOClientStatus.NotConnected
public private(set) var status = SocketIOClientStatus.NotConnected {
didSet {
switch status {
case .Connected:
reconnecting = false
currentReconnectAttempt = 0
default:
break
}
}
}
public var forceNew = false
public var nsp = "/"
@@ -36,7 +46,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
public var reconnects = true
public var reconnectWait = 10
public var sid: String? {
return engine?.sid
return nsp + "#" + (engine?.sid ?? "")
}
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
@@ -46,18 +56,16 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
private var anyHandler: ((SocketAnyEvent) -> Void)?
private var currentReconnectAttempt = 0
private var handlers = [SocketEventHandler]()
private var reconnectTimer: NSTimer?
private var ackHandlers = SocketAckManager()
private var reconnecting = false
private(set) var currentAck = -1
private(set) var handleQueue = dispatch_get_main_queue()
private(set) var reconnectAttempts = -1
var waitingData = [SocketPacket]()
var waitingPackets = [SocketPacket]()
/**
Type safe way to create a new SocketIOClient. opts can be omitted
*/
/// Type safe way to create a new SocketIOClient. opts can be omitted
public init(socketURL: NSURL, options: Set<SocketIOClientOption> = []) {
self.options = options
self.socketURL = socketURL
@@ -94,31 +102,15 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
super.init()
}
/**
Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity.
If using Swift it's recommended to use `init(socketURL: NSURL, options: Set<SocketIOClientOption>)`
*/
/// Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity.
/// If using Swift it's recommended to use `init(socketURL: NSURL, options: Set<SocketIOClientOption>)`
public convenience init(socketURL: NSURL, options: NSDictionary?) {
self.init(socketURL: socketURL, options: options?.toSocketOptionsSet() ?? [])
}
/// Please use the NSURL based init
@available(*, deprecated=5.3)
public convenience init(socketURLString: String, options: Set<SocketIOClientOption> = []) {
guard let url = NSURL(string: socketURLString) else { fatalError("Incorrect url") }
self.init(socketURL: url, options: options)
}
/// Please use the NSURL based init
@available(*, deprecated=5.3)
public convenience init(socketURLString: String, options: NSDictionary?) {
guard let url = NSURL(string: socketURLString) else { fatalError("Incorrect url") }
self.init(socketURL: url, options: options?.toSocketOptionsSet() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Client is being released", type: logType)
engine?.close("Client Deinit")
engine?.disconnect("Client Deinit")
}
private func addEngine() -> SocketEngineSpec {
@@ -129,26 +121,12 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
return engine!
}
private func clearReconnectTimer() {
reconnectTimer?.invalidate()
reconnectTimer = nil
}
@available(*, deprecated=5.3)
public func close() {
disconnect()
}
/**
Connect to the server.
*/
/// Connect to the server.
public func connect() {
connect(timeoutAfter: 0, withTimeoutHandler: nil)
}
/**
Connect to the server. If we aren't connected after timeoutAfter, call handler
*/
/// Connect to the server. If we aren't connected after timeoutAfter, call handler
public func connect(timeoutAfter timeoutAfter: Int, withTimeoutHandler handler: (() -> Void)?) {
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
@@ -161,9 +139,9 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
status = .Connecting
if engine == nil || forceNew {
addEngine().open()
addEngine().connect()
} else {
engine?.open()
engine?.connect()
}
guard timeoutAfter != 0 else { return }
@@ -171,9 +149,9 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
dispatch_after(time, handleQueue) {[weak self] in
if let this = self where this.status != .Connected || this.status != .Closed {
if let this = self where this.status != .Connected && this.status != .Closed {
this.status = .Closed
this.engine?.close("Connect timeout")
this.engine?.disconnect("Connect timeout")
handler?()
}
@@ -186,10 +164,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
return {[weak self, ack = currentAck] timeout, callback in
if let this = self {
this.ackHandlers.addAck(ack, callback: callback)
dispatch_async(this.emitQueue) {
this._emit(items, ack: ack)
}
this._emit(items, ack: ack)
if timeout != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
@@ -205,8 +180,6 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
func didConnect() {
DefaultSocketLogger.Logger.log("Socket connected", type: logType)
status = .Connected
currentReconnectAttempt = 0
clearReconnectTimer()
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
@@ -222,14 +195,12 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
reconnects = false
// Make sure the engine is actually dead.
engine?.close(reason)
engine?.disconnect(reason)
handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
/**
Disconnects the socket. Only reconnect the same socket if you know what you're doing.
Will turn off automatic reconnects.
*/
/// Disconnects the socket. Only reconnect the same socket if you know what you're doing.
/// Will turn off automatic reconnects.
public func disconnect() {
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
@@ -237,54 +208,46 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
didDisconnect("Disconnect")
}
/**
Send a message to the server
*/
/// Send a message to the server
public func emit(event: String, _ items: AnyObject...) {
emit(event, withItems: items)
}
/**
Same as emit, but meant for Objective-C
*/
/// Same as emit, but meant for Objective-C
public func emit(event: String, withItems items: [AnyObject]) {
guard status == .Connected else {
handleEvent("error", data: ["Tried emitting \(event) when not connected"], isInternalMessage: true)
return
}
dispatch_async(emitQueue) {
self._emit([event] + items)
}
_emit([event] + items)
}
/**
Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
an ack.
*/
/// 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...) -> OnAckCallback {
return emitWithAck(event, withItems: items)
}
/**
Same as emitWithAck, but for Objective-C
*/
/// Same as emitWithAck, but for Objective-C
public func emitWithAck(event: String, withItems items: [AnyObject]) -> OnAckCallback {
return createOnAck([event] + items)
}
private func _emit(data: [AnyObject], ack: Int? = nil) {
guard status == .Connected else {
handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
return
dispatch_async(emitQueue) {
guard self.status == .Connected else {
self.handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
return
}
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: self.nsp, ack: false)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting: %@", type: self.logType, args: str)
self.engine?.send(str, withData: packet.binary)
}
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting: %@", type: logType, args: str)
engine?.send(str, withData: packet.binary)
}
// If the server wants to know that the client received data
@@ -302,11 +265,16 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
public func engineDidClose(reason: String) {
waitingData.removeAll()
waitingPackets.removeAll()
if status != .Closed {
status = .NotConnected
}
if status == .Closed || !reconnects {
didDisconnect(reason)
} else if status != .Reconnecting {
} else if !reconnecting {
reconnecting = true
tryReconnectWithReason(reason)
}
}
@@ -320,16 +288,14 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
// Called when the socket gets an ack for something it sent
func handleAck(ack: Int, data: [AnyObject]) {
guard status == .Connected else {return}
guard status == .Connected else { return }
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
ackHandlers.executeAck(ack, items: data)
}
/**
Causes an event to be handled. Only use if you know what you're doing.
*/
/// Causes an event to be handled. Only use if you know what you're doing.
public func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool, withAck ack: Int = -1) {
guard status == .Connected || isInternalMessage else {
return
@@ -346,9 +312,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
}
/**
Leaves nsp and goes back to /
*/
/// Leaves nsp and goes back to /
public func leaveNamespace() {
if nsp != "/" {
engine?.send("1\(nsp)", withData: [])
@@ -356,9 +320,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
}
/**
Joins namespace
*/
/// Joins namespace
public func joinNamespace(namespace: String) {
nsp = namespace
@@ -368,28 +330,22 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
}
/**
Removes handler(s)
*/
/// Removes handler(s) based on name
public func off(event: String) {
DefaultSocketLogger.Logger.log("Removing handler for event: %@", type: logType, args: event)
handlers = handlers.filter { $0.event != event }
}
/**
Removes a handler with the specified UUID gotten from an `on` or `once`
*/
/// Removes a handler with the specified UUID gotten from an `on` or `once`
public func off(id id: NSUUID) {
DefaultSocketLogger.Logger.log("Removing handler with id: %@", type: logType, args: id)
handlers = handlers.filter { $0.id != id }
}
/**
Adds a handler for an event.
Returns: A unique id for the handler
*/
/// Adds a handler for an event.
/// Returns: A unique id for the handler
public func on(event: String, callback: NormalCallback) -> NSUUID {
DefaultSocketLogger.Logger.log("Adding handler for event: %@", type: logType, args: event)
@@ -399,10 +355,8 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
return handler.id
}
/**
Adds a single-use handler for an event.
Returns: A unique id for the handler
*/
/// Adds a single-use handler for an event.
/// Returns: A unique id for the handler
public func once(event: String, callback: NormalCallback) -> NSUUID {
DefaultSocketLogger.Logger.log("Adding once handler for event: %@", type: logType, args: event)
@@ -419,21 +373,11 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
return handler.id
}
/**
Adds a handler that will be called on every event.
*/
/// Adds a handler that will be called on every event.
public func onAny(handler: (SocketAnyEvent) -> Void) {
anyHandler = handler
}
/**
Same as connect
*/
@available(*, deprecated=5.3)
public func open() {
connect()
}
public func parseEngineMessage(msg: String) {
DefaultSocketLogger.Logger.log("Should parse message: %@", type: "SocketIOClient", args: msg)
@@ -448,47 +392,35 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
}
/**
Tries to reconnect to the server.
*/
/// Tries to reconnect to the server.
public func reconnect() {
tryReconnectWithReason("manual reconnect")
guard !reconnecting else { return }
engine?.disconnect("manual reconnect")
}
/**
Removes all handlers.
Can be used after disconnecting to break any potential remaining retain cycles.
*/
/// Removes all handlers.
/// Can be used after disconnecting to break any potential remaining retain cycles.
public func removeAllHandlers() {
handlers.removeAll(keepCapacity: false)
}
private func tryReconnectWithReason(reason: String) {
if reconnectTimer == nil {
if reconnecting {
DefaultSocketLogger.Logger.log("Starting reconnect", type: logType)
handleEvent("reconnect", data: [reason], isInternalMessage: true)
status = .Reconnecting
dispatch_async(dispatch_get_main_queue()) {
self.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self.reconnectWait),
target: self, selector: "_tryReconnect", userInfo: nil, repeats: true)
}
_tryReconnect()
}
}
@objc private func _tryReconnect() {
if status == .Connected {
clearReconnectTimer()
private func _tryReconnect() {
if !reconnecting {
return
}
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
clearReconnectTimer()
didDisconnect("Reconnect Failed")
return
return didDisconnect("Reconnect Failed")
}
DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType)
@@ -497,6 +429,10 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
currentReconnectAttempt += 1
connect()
let dispatchAfter = dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(reconnectWait) * NSEC_PER_SEC))
dispatch_after(dispatchAfter, dispatch_get_main_queue(), _tryReconnect)
}
}
+4 -4
View File
@@ -24,11 +24,11 @@
import Foundation
protocol ClientOption: CustomStringConvertible, Hashable {
protocol ClientOption : CustomStringConvertible, Hashable {
func getSocketIOOptionValue() -> AnyObject
}
public enum SocketIOClientOption: ClientOption {
public enum SocketIOClientOption : ClientOption {
case ConnectParams([String: AnyObject])
case Cookies([NSHTTPCookie])
case DoubleEncodeUTF8(Bool)
@@ -152,7 +152,7 @@ public func ==(lhs: SocketIOClientOption, rhs: SocketIOClientOption) -> Bool {
return lhs.description == rhs.description
}
extension Set where Element: ClientOption {
extension Set where Element : ClientOption {
mutating func insertIgnore(element: Element) {
if !contains(element) {
insert(element)
@@ -161,7 +161,7 @@ extension Set where Element: ClientOption {
}
extension NSDictionary {
static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
private static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
switch (key, value) {
case let ("connectParams", params as [String: AnyObject]):
return .ConnectParams(params)
+2 -4
View File
@@ -24,8 +24,8 @@
import Foundation
@objc public enum SocketIOClientStatus: Int, CustomStringConvertible {
case NotConnected, Closed, Connecting, Connected, Reconnecting
@objc public enum SocketIOClientStatus : Int, CustomStringConvertible {
case NotConnected, Closed, Connecting, Connected
public var description: String {
switch self {
@@ -37,8 +37,6 @@ import Foundation
return "Connecting"
case Connected:
return "Connected"
case Reconnecting:
return "Reconnecting"
}
}
}
+2 -2
View File
@@ -24,7 +24,7 @@
import Foundation
public protocol SocketLogger: class {
public protocol SocketLogger : class {
/// Whether to log or not
var log: Bool {get set}
@@ -54,7 +54,7 @@ public extension SocketLogger {
}
}
class DefaultSocketLogger: SocketLogger {
class DefaultSocketLogger : SocketLogger {
static var Logger: SocketLogger = DefaultSocketLogger()
var log = false
+30 -40
View File
@@ -86,39 +86,29 @@ struct SocketPacket {
}
}
private func completeMessage(message: String, ack: Bool) -> String {
var restOfMessage = ""
private func completeMessage(message: String) -> String {
let restOfMessage: String
if data.count == 0 {
return message + "]"
return message + "[]"
}
for arg in data {
if arg is NSDictionary || arg is [AnyObject] {
do {
let jsonSend = try NSJSONSerialization.dataWithJSONObject(arg,
options: NSJSONWritingOptions(rawValue: 0))
let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding)
restOfMessage += jsonString! + ","
} catch {
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
type: SocketPacket.logType)
}
} else if let str = arg as? String {
restOfMessage += "\"" + ((str["\n"] <~ "\\\\n")["\r"] <~ "\\\\r") + "\","
} else if arg is NSNull {
restOfMessage += "null,"
} else {
restOfMessage += "\(arg),"
do {
let jsonSend = try NSJSONSerialization.dataWithJSONObject(data,
options: NSJSONWritingOptions(rawValue: 0))
guard let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding) else {
return "[]"
}
restOfMessage = jsonString
} catch {
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
type: SocketPacket.logType)
restOfMessage = "[]"
}
if restOfMessage != "" {
restOfMessage.removeAtIndex(restOfMessage.endIndex.predecessor())
}
return message + restOfMessage + "]"
return message + restOfMessage
}
private func createAck() -> String {
@@ -126,19 +116,19 @@ struct SocketPacket {
if type == .Ack {
if nsp == "/" {
message = "3\(id)["
message = "3\(id)"
} else {
message = "3\(nsp),\(id)["
message = "3\(nsp),\(id)"
}
} else {
if nsp == "/" {
message = "6\(binary.count)-\(id)["
message = "6\(binary.count)-\(id)"
} else {
message = "6\(binary.count)-\(nsp),\(id)["
message = "6\(binary.count)-\(nsp),\(id)"
}
}
return completeMessage(message, ack: true)
return completeMessage(message)
}
@@ -148,34 +138,34 @@ struct SocketPacket {
if type == .Event {
if nsp == "/" {
if id == -1 {
message = "2["
message = "2"
} else {
message = "2\(id)["
message = "2\(id)"
}
} else {
if id == -1 {
message = "2\(nsp),["
message = "2\(nsp),"
} else {
message = "2\(nsp),\(id)["
message = "2\(nsp),\(id)"
}
}
} else {
if nsp == "/" {
if id == -1 {
message = "5\(binary.count)-["
message = "5\(binary.count)-"
} else {
message = "5\(binary.count)-\(id)["
message = "5\(binary.count)-\(id)"
}
} else {
if id == -1 {
message = "5\(binary.count)-\(nsp),["
message = "5\(binary.count)-\(nsp),"
} else {
message = "5\(binary.count)-\(nsp),\(id)["
message = "5\(binary.count)-\(nsp),\(id)"
}
}
}
return completeMessage(message, ack: false)
return completeMessage(message)
}
private func createPacketString() -> String {
+13 -12
View File
@@ -22,7 +22,7 @@
import Foundation
protocol SocketParsable: SocketClientSpec {
protocol SocketParsable : SocketClientSpec {
func parseBinaryData(data: NSData)
func parseSocketMessage(message: String)
}
@@ -50,9 +50,9 @@ extension SocketParsable {
case .Ack where isCorrectNamespace(pack.nsp):
handleAck(pack.id, data: pack.data)
case .BinaryEvent where isCorrectNamespace(pack.nsp):
waitingData.append(pack)
waitingPackets.append(pack)
case .BinaryAck where isCorrectNamespace(pack.nsp):
waitingData.append(pack)
waitingPackets.append(pack)
case .Connect:
handleConnect(pack)
case .Disconnect:
@@ -76,7 +76,7 @@ extension SocketParsable {
return .Right(SocketPacket(type: type, nsp: "/"))
}
var namespace: String?
var namespace = "/"
var placeholders = -1
if type == .BinaryEvent || type == .BinaryAck {
@@ -116,26 +116,27 @@ extension SocketParsable {
switch parseData(noPlaceholders) {
case let .Left(err):
// If first you don't succeed, try again
// Errors aren't always enclosed in an array
if case let .Right(data) = parseData("\([noPlaceholders as AnyObject])") {
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace ?? "/", placeholders: placeholders))
nsp: namespace, placeholders: placeholders))
} else {
return .Left(err)
}
case let .Right(data):
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace ?? "/", placeholders: placeholders))
nsp: namespace, placeholders: placeholders))
}
}
// Parses data for events
private func parseData(data: String) -> Either<String, [AnyObject]> {
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
do {
if let arr = try NSJSONSerialization.JSONObjectWithData(stringData!,
options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] {
return .Right(arr)
options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] {
return .Right(arr)
} else {
return .Left("Expected data array")
}
@@ -160,17 +161,17 @@ extension SocketParsable {
}
func parseBinaryData(data: NSData) {
guard !waitingData.isEmpty else {
guard !waitingPackets.isEmpty else {
DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser")
return
}
// Should execute event?
guard waitingData[waitingData.count - 1].addData(data) else {
guard waitingPackets[waitingPackets.count - 1].addData(data) else {
return
}
let packet = waitingData.removeLast()
let packet = waitingPackets.removeLast()
if packet.type != .BinaryAck {
handleEvent(packet.event, data: packet.args ?? [],
+2 -2
View File
@@ -18,8 +18,8 @@ infix operator <~ { associativity none precedence 130 }
private let lock = dispatch_semaphore_create(1)
private var swiftRegexCache = [String: NSRegularExpression]()
internal final class SwiftRegex: NSObject, BooleanType {
var target:String
internal final class SwiftRegex : NSObject, BooleanType {
var target: String
var regex: NSRegularExpression
init(target:String, pattern:String, options:NSRegularExpressionOptions?) {
+74 -48
View File
@@ -109,7 +109,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
public var headers = [String: String]()
public var voipEnabled = false
public var selfSignedSSL = false
private var security: SSLSecurity?
public var security: SSLSecurity?
public var enabledSSLCipherSuites: [SSLCipherSuite]?
public var origin: String?
public var isConnected :Bool {
@@ -167,8 +167,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
public func disconnect(forceTimeout forceTimeout: NSTimeInterval? = nil) {
switch forceTimeout {
case .Some(let seconds) where seconds > 0:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), queue) { [unowned self] in
self.disconnectStream(nil)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), queue) { [weak self] in
self?.disconnectStream(nil)
}
fallthrough
case .None:
@@ -180,30 +180,42 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
}
///write a string to the websocket. This sends it as a text frame.
public func writeString(str: String) {
/**
Write a string to the websocket. This sends it as a text frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter str: The string to write.
- parameter completion: The (optional) completion handler.
*/
public func writeString(str: String, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame)
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame, writeCompletion: completion)
}
///write binary data to the websocket. This sends it as a binary frame.
public func writeData(data: NSData) {
/**
Write binary data to the websocket. This sends it as a binary frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter data: The data to write.
- parameter completion: The (optional) completion handler.
*/
public func writeData(data: NSData, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .BinaryFrame)
dequeueWrite(data, code: .BinaryFrame, writeCompletion: completion)
}
//write a ping to the websocket. This sends it as a control frame.
//yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
public func writePing(data: NSData) {
public func writePing(data: NSData, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .Ping)
dequeueWrite(data, code: .Ping, writeCompletion: completion)
}
//private method that starts the connection
private func createHTTPRequest() {
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
url, kCFHTTPVersion1_1).takeRetainedValue()
url, kCFHTTPVersion1_1).takeRetainedValue()
var port = url.port
if port == nil {
@@ -283,18 +295,18 @@ public class WebSocket : NSObject, NSStreamDelegate {
if let cipherSuites = self.enabledSSLCipherSuites {
if let sslContextIn = CFReadStreamCopyProperty(inputStream, kCFStreamPropertySSLContext) as! SSLContextRef?,
sslContextOut = CFWriteStreamCopyProperty(outputStream, kCFStreamPropertySSLContext) as! SSLContextRef? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
disconnectStream(error)
return
}
if resOut != errSecSuccess {
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
disconnectStream(error)
return
}
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
disconnectStream(error)
return
}
if resOut != errSecSuccess {
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
disconnectStream(error)
return
}
}
}
CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue)
@@ -309,13 +321,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
let bytes = UnsafePointer<UInt8>(data.bytes)
var timeout = 5000000 //wait 5 seconds before giving up
writeQueue.addOperationWithBlock { [weak self] in
guard let this = self else { return }
while !outStream.hasSpaceAvailable {
usleep(100) //wait until the socket is ready
timeout -= 100
if timeout < 0 {
this.cleanupStream()
this.doDisconnect(this.errorWithDetail("write wait timed out", code: 2))
self?.cleanupStream()
self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2))
return
} else if outStream.streamError != nil {
return //disconnectStream will be called.
@@ -352,7 +363,11 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
//disconnect the stream object
private func disconnectStream(error: NSError?) {
writeQueue.waitUntilAllOperationsAreFinished()
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
cleanupStream()
doDisconnect(error)
}
@@ -425,7 +440,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
case -1:
fragBuffer = NSData(bytes: buffer, length: bufferLen)
break //do nothing, we are going to collect more data
break //do nothing, we are going to collect more data
default:
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
}
@@ -544,10 +559,10 @@ public class WebSocket : NSObject, NSStreamDelegate {
let isControlFrame = (receivedOpcode == .ConnectionClose || receivedOpcode == .Ping)
if !isControlFrame && (receivedOpcode != .BinaryFrame && receivedOpcode != .ContinueFrame &&
receivedOpcode != .TextFrame && receivedOpcode != .Pong) {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
writeError(errCode)
return
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
writeError(errCode)
return
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.ProtocolError.rawValue
@@ -600,7 +615,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
var data: NSData!
let data: NSData
if len < 0 {
len = 0
data = NSData()
@@ -736,7 +751,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
}
///used to write things to the stream
private func dequeueWrite(data: NSData, code: OpCode) {
private func dequeueWrite(data: NSData, code: OpCode, writeCompletion: (() -> ())? = nil) {
writeQueue.addOperationWithBlock { [weak self] in
//stream isn't ready, let's wait
guard let s = self else { return }
@@ -785,6 +800,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
total += len
}
if total >= offset {
if let queue = self?.queue, callback = writeCompletion {
dispatch_async(queue) {
callback()
}
}
break
}
}
@@ -814,7 +835,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
private class SSLCert {
public class SSLCert {
var certData: NSData?
var key: SecKeyRef?
@@ -825,7 +846,7 @@ private class SSLCert {
- returns: a representation security object to be used with
*/
init(data: NSData) {
public init(data: NSData) {
self.certData = data
}
@@ -836,13 +857,13 @@ private class SSLCert {
- returns: a representation security object to be used with
*/
init(key: SecKeyRef) {
public init(key: SecKeyRef) {
self.key = key
}
}
private class SSLSecurity {
var validatedDN = true //should the domain name be validated?
public class SSLSecurity {
public var validatedDN = true //should the domain name be validated?
var isReady = false //is the key processing done?
var certificates: [NSData]? //the certificates
@@ -856,10 +877,11 @@ private class SSLSecurity {
- returns: a representation security object to be used with
*/
convenience init(usePublicKeys: Bool = false) {
public convenience init(usePublicKeys: Bool = false) {
let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".")
let certs = paths.reduce([SSLCert]()) { (var certs: [SSLCert], path: String) -> [SSLCert] in
let certs = paths.reduce([SSLCert]()) { (certs: [SSLCert], path: String) -> [SSLCert] in
var certs = certs
if let data = NSData(contentsOfFile: path) {
certs.append(SSLCert(data: data))
}
@@ -877,12 +899,13 @@ private class SSLSecurity {
- returns: a representation security object to be used with
*/
init(certs: [SSLCert], usePublicKeys: Bool) {
public init(certs: [SSLCert], usePublicKeys: Bool) {
self.usePublicKeys = usePublicKeys
if self.usePublicKeys {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) {
let pubKeys = certs.reduce([SecKeyRef]()) { (var pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in
let pubKeys = certs.reduce([SecKeyRef]()) { (pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in
var pubKeys = pubKeys
if let data = cert.certData where cert.key == nil {
cert.key = self.extractPublicKey(data)
}
@@ -896,7 +919,8 @@ private class SSLSecurity {
self.isReady = true
}
} else {
let certificates = certs.reduce([NSData]()) { (var certificates: [NSData], cert: SSLCert) -> [NSData] in
let certificates = certs.reduce([NSData]()) { (certificates: [NSData], cert: SSLCert) -> [NSData] in
var certificates = certificates
if let data = cert.certData {
certificates.append(data)
}
@@ -915,7 +939,7 @@ private class SSLSecurity {
- returns: if the key was successfully validated
*/
func isValid(trust: SecTrustRef, domain: String?) -> Bool {
public func isValid(trust: SecTrustRef, domain: String?) -> Bool {
var tries = 0
while(!self.isReady) {
@@ -1010,7 +1034,8 @@ private class SSLSecurity {
- returns: the certificate chain for the trust
*/
func certificateChainForTrust(trust: SecTrustRef) -> [NSData] {
let certificates = (0..<SecTrustGetCertificateCount(trust)).reduce([NSData]()) { (var certificates: [NSData], index: Int) -> [NSData] in
let certificates = (0..<SecTrustGetCertificateCount(trust)).reduce([NSData]()) { (certificates: [NSData], index: Int) -> [NSData] in
var certificates = certificates
let cert = SecTrustGetCertificateAtIndex(trust, index)
certificates.append(SecCertificateCopyData(cert!))
return certificates
@@ -1028,7 +1053,8 @@ private class SSLSecurity {
*/
func publicKeyChainForTrust(trust: SecTrustRef) -> [SecKeyRef] {
let policy = SecPolicyCreateBasicX509()
let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKeyRef]()) { (var keys: [SecKeyRef], index: Int) -> [SecKeyRef] in
let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKeyRef]()) { (keys: [SecKeyRef], index: Int) -> [SecKeyRef] in
var keys = keys
let cert = SecTrustGetCertificateAtIndex(trust, index)
if let key = extractPublicKeyFromCert(cert!, policy: policy) {
keys.append(key)