Compare commits

..
17 Commits
Author SHA1 Message Date
Erik Little fdb00d63ff Merge branch 'enhorn-swift2.3' into swift2.3
* enhorn-swift2.3:
  Changes so the legacy build setting is set on the project, instead of each target.
  Adds the legacy option to the build settings, so the project compiles.
2016-09-12 09:30:10 -04:00
Robin Enhorn a009afc6de Changes so the legacy build setting is set on the project, instead of each target. 2016-09-12 15:23:31 +02:00
Robin Enhorn c4b1f29c80 Adds the legacy option to the build settings, so the project compiles. 2016-09-12 15:21:23 +02:00
Erik 404fa8cdfa Merge branch 'development' into swift2.3
* development:
  change spm name
  Modify mac version base mac os 10.9
  Fix cocoapods name
  fix sid bug
  Fix socketio/socket.io-client-swift#472
  bump version
  Refactor engine. Fix infinite recursion in configuration
  Don't send whole packet to handleConnect
  Update readme
  bump version
  update readme
  Renamed modules to make then consistent.
  rename engine init
  Revert "travis plz"
  travis plz
2016-09-02 17:40:58 -04:00
Erik e3c6993f75 merge development 2016-08-14 10:39:13 -04:00
Erik a0c6b8b622 Merge develop 2016-08-11 21:38:57 -04:00
Erik ea1fc1b0cc Merge branch 'development' into swift2.3
* development:
  bump version
  add check for bad paths
  Fix socketpollable crashing
  make nonobjc
  More privatisation
  Making publicKeyChainForTrust() private.
  api extensions doesn't seem to fail for me
  update readme
  don't use api extensions only
2016-07-29 19:43:18 -04:00
Erik a74d2fba85 Merge branch 'evanbrass-fix-optional-unwrapping' into swift2.3
* evanbrass-fix-optional-unwrapping:
  Fix errors with force unwrapping optionals
2016-07-28 21:19:47 -04:00
Erik dbbed11a03 fix warning 2016-07-28 21:19:40 -04:00
Evan Brass 8f0a7c8f82 Fix errors with force unwrapping optionals
- Removing these fixed compile errors on swift 2.3.
2016-07-28 12:23:03 -04:00
Erik Little 4d12f9f510 Merge branch 'development' into swift2.3
* development:
  don't try and start server
2016-07-21 10:51:54 -04:00
Erik Little a2969680e8 Merge branch 'development' into swift2.3
* development:
  change travis config
  remove log for dorequest
2016-07-21 10:47:39 -04:00
Erik 744d6bd062 Merge branch 'development' into swift2.3
* development:
  bump version
  fix swiftpm
  rename variable
  Enable APPLICATION_EXTENSION_API_ONLY
  fix method call
  fixes
  don't stall queues
  hopefully fix race condition in acks
  refactors
  Update README.md
  refactors, rename file
  refactoring
  refactor some serialization into methods
2016-07-20 11:32:38 -04:00
Erik 5814e8d275 Merge branch 'master' into swift2.3
* master:
  unknown message isn't fatal
  bump version
  notify client when engine disconnects
2016-06-24 02:49:14 -04:00
Erik be76a1607c merge master 2016-06-17 10:16:52 -04:00
Erik Little c1a451f314 Merge pull request #398 from davbeck/swift2.3
Updated code to support Swift 2.3
2016-06-16 19:07:28 -04:00
David Beck 0e38039a0c Updated code to support Swift 2.3 2016-06-14 07:31:15 -07:00
37 changed files with 1109 additions and 1246 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
3.0
+2 -6
View File
@@ -1,13 +1,9 @@
language: objective-c
xcode_project: Socket.IO-Client-Swift.xcodeproj # path to your xcodeproj folder
xcode_scheme: SocketIO-iOS
osx_image: xcode8
osx_image: xcode7.3
branches:
only:
- master
- development
before_install:
- brew update
- brew outdated xctool || brew upgrade xctool
# script: xctool -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac build test -parallelize
script: xcodebuild -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac build test
script: xctool -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac build test -parallelize
+40 -43
View File
@@ -6,7 +6,8 @@ Socket.IO-client for iOS/OS X.
##Example
```swift
import SocketIO
let socket = SocketIOClient(socketURL: URL(string: "http://localhost:8080")!, config: [.log(true), .forcePolling(true)])
let socket = SocketIOClient(socketURL: NSURL(string: "http://localhost:8080")!, config: [.Log(true), .ForcePolling(true)])
socket.on("connect") {data, ack in
print("socket connected")
@@ -14,7 +15,7 @@ socket.on("connect") {data, ack in
socket.on("currentAmount") {data, ack in
if let cur = data[0] as? Double {
socket.emitWithAck("canUpdate", cur)(0) {data in
socket.emitWithAck("canUpdate", cur)(timeoutAfter: 0) {data in
socket.emit("update", ["amount": cur + 2.50])
}
@@ -57,17 +58,13 @@ SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:url config:@{
- Can be used from Objective-C
##Installation
Requires Swift 3/Xcode 8.x
Requires Swift 2.2/Xcode 7.3
If you need swift 2.3 use the swift2.3 branch (Pre-Swift 3 support is no longer maintained)
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 2.2 use 7.x (Pre-Swift 3 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)
If you need Swift 2.1 use v5.5.0 (Pre-Swift 2.2 support is no longer maintained)
If you need Swift 1.2 use v2.4.5 (Pre-Swift 2 support is no longer maintained)
If you need Swift 1.1 use v1.5.2. (Pre-Swift 1.2 support is no longer maintained)
If you need Swift 1.1/Xcode 6.2 use v1.5.2. (Pre-Swift 1.2 support is no longer maintained)
Manually (iOS 7+)
-----------------
@@ -83,18 +80,18 @@ import PackageDescription
let package = Package(
name: "YourSocketIOProject",
dependencies: [
.Package(url: "https://github.com/socketio/socket.io-client-swift", majorVersion: 8)
.Package(url: "https://github.com/socketio/socket.io-client-swift", majorVersion: 6)
]
)
```
Then import `import SocketIO`.
Then import `import SocketIOClientSwift`.
Carthage
-----------------
Add this line to your `Cartfile`:
```
github "socketio/socket.io-client-swift" ~> 8.0.2 # Or latest version
github "socketio/socket.io-client-swift" ~> 7.0.3 # Or latest version
```
Run `carthage update --platform ios,macosx`.
@@ -107,7 +104,7 @@ Create `Podfile` and add `pod 'Socket.IO-Client-Swift'`:
use_frameworks!
target 'YourApp' do
pod 'Socket.IO-Client-Swift', '~> 8.0.2' # Or latest version
pod 'Socket.IO-Client-Swift', '~> 7.0.3' # Or latest version
end
```
@@ -136,7 +133,7 @@ CocoaSeeds
Add this line to your `Seedfile`:
```
github "socketio/socket.io-client-swift", "v8.0.2", :files => "Source/*.swift" # Or latest version
github "socketio/socket.io-client-swift", "v7.0.3", :files => "Source/*.swift" # Or latest version
```
Run `seed install`.
@@ -154,43 +151,43 @@ Options
All options are a case of SocketIOClientOption. To get the Objective-C Option, convert the name to lowerCamelCase.
```swift
case connectParams([String: AnyObject]) // Dictionary whose contents will be passed with the connection.
case cookies([NSHTTPCookie]) // An array of NSHTTPCookies. Passed during the handshake. Default is nil.
case doubleEncodeUTF8(Bool) // Whether or not to double encode utf8. If using the node based server this should be true. Default is true.
case extraHeaders([String: String]) // Adds custom headers to the initial request. Default is nil.
case forcePolling(Bool) // `true` forces the client to use xhr-polling. Default is `false`
case forceNew(Bool) // Will a create a new engine for each connect. Useful if you find a bug in the engine related to reconnects
case forceWebsockets(Bool) // `true` forces the client to use WebSockets. Default is `false`
case handleQueue(dispatch_queue_t) // The dispatch queue that handlers are run on. Default is the main queue.
case log(Bool) // If `true` socket will log debug messages. Default is false.
case logger(SocketLogger) // Custom logger that conforms to SocketLogger. Will use the default logging otherwise.
case nsp(String) // The namespace to connect to. Must begin with /. Default is `/`
case path(String) // If the server uses a custom path. ex: `"/swift/"`. Default is `""`
case reconnects(Bool) // Whether to reconnect on server lose. Default is `true`
case reconnectAttempts(Int) // How many times to reconnect. Default is `-1` (infinite tries)
case reconnectWait(Int) // Amount of time to wait between reconnects. Default is `10`
case sessionDelegate(NSURLSessionDelegate) // Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
case secure(Bool) // If the connection should use TLS. Default is false.
case security(SSLSecurity) // Allows you to set which certs are valid. Useful for SSL pinning.
case selfSigned(Bool) // Sets WebSocket.selfSignedSSL. Use this if you're using self-signed certs.
case voipEnabled(Bool) // Only use this option if you're using the client with VoIP services. Changes the way the WebSocket is created. Default is false
case ConnectParams([String: AnyObject]) // Dictionary whose contents will be passed with the connection.
case Cookies([NSHTTPCookie]) // An array of NSHTTPCookies. Passed during the handshake. Default is nil.
case DoubleEncodeUTF8(Bool) // Whether or not to double encode utf8. If using the node based server this should be true. Default is true.
case ExtraHeaders([String: String]) // Adds custom headers to the initial request. Default is nil.
case ForcePolling(Bool) // `true` forces the client to use xhr-polling. Default is `false`
case ForceNew(Bool) // Will a create a new engine for each connect. Useful if you find a bug in the engine related to reconnects
case ForceWebsockets(Bool) // `true` forces the client to use WebSockets. Default is `false`
case HandleQueue(dispatch_queue_t) // The dispatch queue that handlers are run on. Default is the main queue.
case Log(Bool) // If `true` socket will log debug messages. Default is false.
case Logger(SocketLogger) // Custom logger that conforms to SocketLogger. Will use the default logging otherwise.
case Nsp(String) // The namespace to connect to. Must begin with /. Default is `/`
case Path(String) // If the server uses a custom path. ex: `"/swift/"`. Default is `""`
case Reconnects(Bool) // Whether to reconnect on server lose. Default is `true`
case ReconnectAttempts(Int) // How many times to reconnect. Default is `-1` (infinite tries)
case ReconnectWait(Int) // Amount of time to wait between reconnects. Default is `10`
case SessionDelegate(NSURLSessionDelegate) // Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
case Secure(Bool) // If the connection should use TLS. Default is false.
case Security(SSLSecurity) // Allows you to set which certs are valid. Useful for SSL pinning.
case SelfSigned(Bool) // Sets WebSocket.selfSignedSSL. Use this if you're using self-signed certs.
case VoipEnabled(Bool) // Only use this option if you're using the client with VoIP services. Changes the way the WebSocket is created. Default is false
```
Methods
-------
1. `on(_ event: String, callback: NormalCallback) -> NSUUID` - 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. Returns a unique id for the handler.
2. `once(_ event: String, callback: NormalCallback) -> NSUUID` - Adds a handler that will only be executed once. Returns a unique id for the handler.
1. `on(event: String, callback: NormalCallback) -> NSUUID` - 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. Returns a unique id for the handler.
2. `once(event: String, callback: NormalCallback) -> NSUUID` - Adds a handler that will only be executed once. Returns a unique id for the handler.
3. `onAny(callback:((event: String, items: AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
4. `emit(_ event: String, _ items: AnyObject...)` - Sends a message. Can send multiple items.
5. `emit(_ event: String, withItems items: [AnyObject])` - `emit` for Objective-C
6. `emitWithAck(_ event: String, _ items: AnyObject...) -> (timeoutAfter: 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.
7. `emitWithAck(_ 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.
4. `emit(event: String, _ items: AnyObject...)` - Sends a message. Can send multiple items.
5. `emit(event: String, withItems items: [AnyObject])` - `emit` for Objective-C
6. `emitWithAck(event: String, _ items: AnyObject...) -> (timeoutAfter: 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.
7. `emitWithAck(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.
8. `connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
9. `connect(timeoutAfter timeoutAfter: Int, withTimeoutHandler handler: (() -> Void)?)` - Connect to the server. If it isn't connected after timeoutAfter seconds, the handler is called.
10. `disconnect()` - Closes the socket. Reopening a disconnected socket is not fully tested.
11. `reconnect()` - Causes the client to reconnect to the server.
12. `joinNamespace(_ namespace: String)` - Causes the client to join namespace. Shouldn't need to be called unless you change namespaces manually.
12. `joinNamespace(namespace: String)` - Causes the client to join namespace. Shouldn't need to be called unless you change namespaces manually.
13. `leaveNamespace()` - Causes the client to leave the nsp and go back to /
14. `off(_ event: String)` - Removes all event handlers for event.
14. `off(event: String)` - Removes all event handlers for event.
15. `off(id id: NSUUID)` - Removes the event that corresponds to id.
16. `removeAllHandlers()` - Removes all handlers.
+3 -3
View File
@@ -1,7 +1,7 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.module_name = "SocketIO"
s.version = "8.0.2"
s.version = "7.0.3"
s.summary = "Socket.IO-client for iOS and OS X"
s.description = <<-DESC
Socket.IO-client for iOS and OS X.
@@ -12,9 +12,9 @@ Pod::Spec.new do |s|
s.license = { :type => 'MIT' }
s.author = { "Erik" => "nuclear.ace@gmail.com" }
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.osx.deployment_target = '10.9'
s.tvos.deployment_target = '9.0'
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v8.0.2' }
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v7.0.3' }
s.source_files = "Source/**/*.swift"
s.requires_arc = true
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
@@ -531,9 +531,8 @@
572EF20E1B51F12F00EEBB58 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftMigration = 0730;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 0800;
LastUpgradeCheck = 0720;
TargetAttributes = {
572EF2181B51F16C00EEBB58 = {
CreatedOnToolsVersion = 6.4;
@@ -774,31 +773,16 @@
isa = XCBuildConfiguration;
buildSettings = {
BITCODE_GENERATION_MODE = bitcode;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "Developer ID Application";
ENABLE_BITCODE = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MACOSX_DEPLOYMENT_TARGET = 10.10;
ONLY_ACTIVE_ARCH = YES;
PRODUCT_NAME = SocketIO;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
SWIFT_VERSION = 2.3;
TVOS_DEPLOYMENT_TARGET = 9.0;
WATCHOS_DEPLOYMENT_TARGET = 2.0;
};
@@ -808,28 +792,13 @@
isa = XCBuildConfiguration;
buildSettings = {
BITCODE_GENERATION_MODE = bitcode;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "Developer ID Application";
ENABLE_BITCODE = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MACOSX_DEPLOYMENT_TARGET = 10.10;
PRODUCT_NAME = SocketIO;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 3.0;
SWIFT_VERSION = 2.3;
TVOS_DEPLOYMENT_TARGET = 9.0;
WATCHOS_DEPLOYMENT_TARGET = 2.0;
};
@@ -886,7 +855,6 @@
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
@@ -937,7 +905,6 @@
PRODUCT_BUNDLE_IDENTIFIER = io.socket.SocketIOClientSwift;
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic";
@@ -1094,7 +1061,6 @@
SDKROOT = macosx;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
@@ -1146,7 +1112,6 @@
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
SDKROOT = macosx;
SKIP_INSTALL = YES;
SWIFT_VERSION = 3.0;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
@@ -1203,7 +1168,7 @@
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
SWIFT_VERSION = 2.3;
};
name = Debug;
};
@@ -1250,7 +1215,7 @@
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
SWIFT_VERSION = 3.0;
SWIFT_VERSION = 2.3;
};
name = Release;
};
+5 -5
View File
@@ -13,14 +13,14 @@ class SocketAckManagerTest: XCTestCase {
var ackManager = SocketAckManager()
func testAddAcks() {
let callbackExpection = self.expectation(description: "callbackExpection")
let callbackExpection = self.expectationWithDescription("callbackExpection")
let itemsArray = ["Hi", "ho"]
func callback(_ items: [Any]) {
func callback(items: [AnyObject]) {
callbackExpection.fulfill()
}
ackManager.addAck(1, callback: callback)
ackManager.executeAck(1, with: itemsArray, onQueue: DispatchQueue.main)
waitForExpectations(timeout: 3.0, handler: nil)
ackManager.executeAck(1, items: itemsArray, onQueue: dispatch_get_main_queue())
waitForExpectationsWithTimeout(3.0, handler: nil)
}
}
+22 -24
View File
@@ -10,8 +10,8 @@ import XCTest
@testable import SocketIO
class SocketBasicPacketTest: XCTestCase {
let data = "test".data(using: String.Encoding.utf8)!
let data2 = "test2".data(using: String.Encoding.utf8)!
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
func testEmpyEmit() {
let expectedSendString = "2[\"test\"]"
@@ -23,7 +23,7 @@ class SocketBasicPacketTest: XCTestCase {
func testNullEmit() {
let expectedSendString = "2[\"test\",null]"
let sendData: [Any] = ["test", NSNull()]
let sendData = ["test", NSNull()]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -46,8 +46,8 @@ class SocketBasicPacketTest: XCTestCase {
}
func testJSONEmit() {
let expectedSendString = "2[\"test\",{\"null\":null,\"hello\":1,\"test\":\"hello\",\"foobar\":true}]"
let sendData: [Any] = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
let expectedSendString = "2[\"test\",{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
let sendData = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -55,15 +55,15 @@ class SocketBasicPacketTest: XCTestCase {
func testArrayEmit() {
let expectedSendString = "2[\"test\",[\"hello\",1,{\"test\":\"test\"}]]"
let sendData: [Any] = ["test", ["hello", 1, ["test": "test"]]]
let sendData = ["test", ["hello", 1, ["test": "test"]]]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testBinaryEmit() {
let expectedSendString = "51-[\"test\",{\"_placeholder\":true,\"num\":0}]"
let sendData: [Any] = ["test", data]
let expectedSendString = "51-[\"test\",{\"num\":0,\"_placeholder\":true}]"
let sendData = ["test", data]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -71,12 +71,12 @@ class SocketBasicPacketTest: XCTestCase {
}
func testMultipleBinaryEmit() {
let expectedSendString = "52-[\"test\",{\"data2\":{\"_placeholder\":true,\"num\":0},\"data1\":{\"_placeholder\":true,\"num\":1}}]"
let sendData: [Any] = ["test", ["data1": data, "data2": data2] as NSDictionary]
let expectedSendString = "52-[\"test\",{\"data1\":{\"num\":0,\"_placeholder\":true},\"data2\":{\"num\":1,\"_placeholder\":true}}]"
let sendData = ["test", ["data1": data, "data2": data2]]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
XCTAssertEqual(packet.binary, [data2, data])
XCTAssertEqual(packet.binary, [data, data2])
}
func testEmitWithAck() {
@@ -84,14 +84,12 @@ class SocketBasicPacketTest: XCTestCase {
let sendData = ["test"]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString,
expectedSendString)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testEmitDataWithAck() {
let expectedSendString = "51-0[\"test\",{\"_placeholder\":true,\"num\":0}]"
let sendData: [Any] = ["test", data]
let expectedSendString = "51-0[\"test\",{\"num\":0,\"_placeholder\":true}]"
let sendData = ["test", data]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -123,7 +121,7 @@ class SocketBasicPacketTest: XCTestCase {
}
func testJSONAck() {
let expectedSendString = "30[{\"null\":null,\"hello\":1,\"test\":\"hello\",\"foobar\":true}]"
let expectedSendString = "30[{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
let sendData = [["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
@@ -131,7 +129,7 @@ class SocketBasicPacketTest: XCTestCase {
}
func testBinaryAck() {
let expectedSendString = "61-0[{\"_placeholder\":true,\"num\":0}]"
let expectedSendString = "61-0[{\"num\":0,\"_placeholder\":true}]"
let sendData = [data]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
@@ -140,7 +138,7 @@ class SocketBasicPacketTest: XCTestCase {
}
func testMultipleBinaryAck() {
let expectedSendString = "62-0[{\"data2\":{\"_placeholder\":true,\"num\":0},\"data1\":{\"_placeholder\":true,\"num\":1}}]"
let expectedSendString = "62-0[{\"data2\":{\"num\":0,\"_placeholder\":true},\"data1\":{\"num\":1,\"_placeholder\":true}}]"
let sendData = [["data1": data, "data2": data2]]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
@@ -149,15 +147,15 @@ class SocketBasicPacketTest: XCTestCase {
}
func testBinaryStringPlaceholderInMessage() {
let engineString = "52-[\"test\",\"~~0\",{\"num\":0,\"_placeholder\":true},{\"_placeholder\":true,\"num\":1}]"
let socket = SocketIOClient(socketURL: URL(string: "http://localhost/")!)
let engineString = "52-[\"test\",\"~~0\",{\"num\":0,\"_placeholder\":true},{\"num\":1,\"_placeholder\":true}]"
let socket = SocketIOClient(socketURL: NSURL())
socket.setTestable()
if case let .right(packet) = socket.parseString(engineString) {
if case let .Right(packet) = socket.parseString(engineString) {
var packet = packet
XCTAssertEqual(packet.event, "test")
_ = packet.addData(data)
_ = packet.addData(data2)
packet.addData(data)
packet.addData(data2)
XCTAssertEqual(packet.args[0] as? String, "~~0")
} else {
XCTFail()
+16 -35
View File
@@ -15,24 +15,24 @@ class SocketEngineTest: XCTestCase {
override func setUp() {
super.setUp()
client = SocketIOClient(socketURL: URL(string: "http://localhost")!)
engine = SocketEngine(client: client, url: URL(string: "http://localhost")!, options: nil)
client = SocketIOClient(socketURL: NSURL(string: "http://localhost")!)
engine = SocketEngine(client: client, url: NSURL(string: "http://localhost")!, options: nil)
client.setTestable()
}
func testBasicPollingMessage() {
let expect = expectation(description: "Basic polling test")
let expectation = expectationWithDescription("Basic polling test")
client.on("blankTest") {data, ack in
expect.fulfill()
expectation.fulfill()
}
engine.parsePollingMessage("15:42[\"blankTest\"]")
waitForExpectations(timeout: 3, handler: nil)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testTwoPacketsInOnePollTest() {
let finalExpectation = expectation(description: "Final packet in poll test")
let finalExpectation = expectationWithDescription("Final packet in poll test")
var gotBlank = false
client.on("blankTest") {data, ack in
@@ -40,7 +40,7 @@ class SocketEngineTest: XCTestCase {
}
client.on("stringTest") {data, ack in
if let str = data[0] as? String, gotBlank {
if let str = data[0] as? String where gotBlank {
if str == "hello" {
finalExpectation.fulfill()
}
@@ -48,43 +48,43 @@ class SocketEngineTest: XCTestCase {
}
engine.parsePollingMessage("15:42[\"blankTest\"]24:42[\"stringTest\",\"hello\"]")
waitForExpectations(timeout: 3, handler: nil)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testEngineDoesErrorOnUnknownTransport() {
let finalExpectation = expectation(description: "Unknown Transport")
let finalExpectation = expectationWithDescription("Unknown Transport")
client.on("error") {data, ack in
if let error = data[0] as? String, error == "Unknown transport" {
if let error = data[0] as? String where error == "Unknown transport" {
finalExpectation.fulfill()
}
}
engine.parseEngineMessage("{\"code\": 0, \"message\": \"Unknown transport\"}", fromPolling: false)
waitForExpectations(timeout: 3, handler: nil)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testEngineDoesErrorOnUnknownMessage() {
let finalExpectation = expectation(description: "Engine Errors")
let finalExpectation = expectationWithDescription("Engine Errors")
client.on("error") {data, ack in
finalExpectation.fulfill()
}
engine.parseEngineMessage("afafafda", fromPolling: false)
waitForExpectations(timeout: 3, handler: nil)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testEngineDecodesUTF8Properly() {
let expect = expectation(description: "Engine Decodes utf8")
let expectation = expectationWithDescription("Engine Decodes utf8")
client.on("stringTest") {data, ack in
XCTAssertEqual(data[0] as? String, "lïne one\nlīne \rtwo", "Failed string test")
expect.fulfill()
expectation.fulfill()
}
engine.parsePollingMessage("41:42[\"stringTest\",\"lïne one\\nlīne \\rtwo\"]")
waitForExpectations(timeout: 3, handler: nil)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testEncodeURLProperly() {
@@ -102,23 +102,4 @@ class SocketEngineTest: XCTestCase {
XCTAssertEqual(engine.urlPolling.query, "transport=polling&b64=1&forbidden=%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D%22%20%7B%7D")
XCTAssertEqual(engine.urlWebSocket.query, "transport=websocket&forbidden=%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D%22%20%7B%7D")
}
func testBase64Data() {
let expect = expectation(description: "Engine Decodes base64 data")
let b64String = "b4aGVsbG8NCg=="
let packetString = "451-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0}}]"
client.on("test") {data, ack in
if let data = data[0] as? Data, let string = String(data: data, encoding: .utf8) {
XCTAssertEqual(string, "hello")
}
expect.fulfill()
}
engine.parseEngineMessage(packetString, fromPolling: false)
engine.parseEngineMessage(b64String, fromPolling: false)
waitForExpectations(timeout: 3, handler: nil)
}
}
@@ -15,16 +15,16 @@ class TestSocketIOClientConfiguration: XCTestCase {
override func setUp() {
super.setUp()
config = [.log(false), .forceNew(true)]
config = [.Log(false), .ForceNew(true)]
}
func testReplaceSameOption() {
config.insert(.log(true))
config.insert(.Log(true))
XCTAssertEqual(config.count, 2)
switch config[0] {
case let .log(log):
case let .Log(log):
XCTAssertTrue(log)
default:
XCTFail()
@@ -32,12 +32,12 @@ class TestSocketIOClientConfiguration: XCTestCase {
}
func testIgnoreIfExisting() {
config.insert(.forceNew(false), replacing: false)
config.insert(.ForceNew(false), replacing: false)
XCTAssertEqual(config.count, 2)
switch config[1] {
case let .forceNew(new):
case let .ForceNew(new):
XCTAssertTrue(new)
default:
XCTFail()
@@ -10,12 +10,12 @@ import XCTest
@testable import SocketIO
class SocketNamespacePacketTest: XCTestCase {
let data = "test".data(using: String.Encoding.utf8)!
let data2 = "test2".data(using: String.Encoding.utf8)!
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
func testEmpyEmit() {
let expectedSendString = "2/swift,[\"test\"]"
let sendData: [Any] = ["test"]
let sendData = ["test"]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -23,7 +23,7 @@ class SocketNamespacePacketTest: XCTestCase {
func testNullEmit() {
let expectedSendString = "2/swift,[\"test\",null]"
let sendData: [Any] = ["test", NSNull()]
let sendData = ["test", NSNull()]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -31,32 +31,31 @@ class SocketNamespacePacketTest: XCTestCase {
func testStringEmit() {
let expectedSendString = "2/swift,[\"test\",\"foo bar\"]"
let sendData: [Any] = ["test", "foo bar"]
let sendData = ["test", "foo bar"]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testJSONEmit() {
let expectedSendString = "2/swift,[\"test\",{\"null\":null,\"test\":\"hello\",\"hello\":1,\"foobar\":true}]"
let sendData: [Any] = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()] as NSDictionary]
let expectedSendString = "2/swift,[\"test\",{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
let sendData = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testArrayEmit() {
let expectedSendString = "2/swift,[\"test\",[\"hello\",1,{\"test\":\"test\"},true]]"
let sendData: [Any] = ["test", ["hello", 1, ["test": "test"], true]]
let expectedSendString = "2/swift,[\"test\",[\"hello\",1,{\"test\":\"test\"}]]"
let sendData = ["test", ["hello", 1, ["test": "test"]]]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testBinaryEmit() {
let expectedSendString = "51-/swift,[\"test\",{\"_placeholder\":true,\"num\":0}]"
let sendData: [Any] = ["test", data]
let expectedSendString = "51-/swift,[\"test\",{\"num\":0,\"_placeholder\":true}]"
let sendData = ["test", data]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -64,12 +63,12 @@ class SocketNamespacePacketTest: XCTestCase {
}
func testMultipleBinaryEmit() {
let expectedSendString = "52-/swift,[\"test\",{\"data2\":{\"_placeholder\":true,\"num\":0},\"data1\":{\"_placeholder\":true,\"num\":1}}]"
let sendData: [Any] = ["test", ["data1": data, "data2": data2] as NSDictionary]
let expectedSendString = "52-/swift,[\"test\",{\"data1\":{\"num\":0,\"_placeholder\":true},\"data2\":{\"num\":1,\"_placeholder\":true}}]"
let sendData = ["test", ["data1": data, "data2": data2]]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
XCTAssertEqual(packet.binary, [data2, data])
XCTAssertEqual(packet.binary, [data, data2])
}
func testEmitWithAck() {
@@ -81,8 +80,8 @@ class SocketNamespacePacketTest: XCTestCase {
}
func testEmitDataWithAck() {
let expectedSendString = "51-/swift,0[\"test\",{\"_placeholder\":true,\"num\":0}]"
let sendData: [Any] = ["test", data]
let expectedSendString = "51-/swift,0[\"test\",{\"num\":0,\"_placeholder\":true}]"
let sendData = ["test", data]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -114,7 +113,7 @@ class SocketNamespacePacketTest: XCTestCase {
}
func testJSONAck() {
let expectedSendString = "3/swift,0[{\"null\":null,\"hello\":1,\"test\":\"hello\",\"foobar\":true}]"
let expectedSendString = "3/swift,0[{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
let sendData = [["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
@@ -122,7 +121,7 @@ class SocketNamespacePacketTest: XCTestCase {
}
func testBinaryAck() {
let expectedSendString = "61-/swift,0[{\"_placeholder\":true,\"num\":0}]"
let expectedSendString = "61-/swift,0[{\"num\":0,\"_placeholder\":true}]"
let sendData = [data]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
@@ -131,7 +130,7 @@ class SocketNamespacePacketTest: XCTestCase {
}
func testMultipleBinaryAck() {
let expectedSendString = "62-/swift,0[{\"data2\":{\"_placeholder\":true,\"num\":0},\"data1\":{\"_placeholder\":true,\"num\":1}}]"
let expectedSendString = "62-/swift,0[{\"data2\":{\"num\":0,\"_placeholder\":true},\"data1\":{\"num\":1,\"_placeholder\":true}}]"
let sendData = [["data1": data, "data2": data2]]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
+3 -3
View File
@@ -31,11 +31,11 @@
}
- (void)testEmitSyntax {
[self.socket emit:@"testEmit" with:@[@YES]];
[self.socket emit:@"testEmit" withItems:@[@YES]];
}
- (void)testEmitWithAckSyntax {
[self.socket emitWithAck:@"testAckEmit" with:@[@YES]](0, ^(NSArray* data) {
[self.socket emitWithAck:@"testAckEmit" withItems:@[@YES]](0, ^(NSArray* data) {
});
}
@@ -47,7 +47,7 @@
- (void)testSocketManager {
SocketClientManager* manager = [SocketClientManager sharedManager];
[manager addSocket:self.socket labeledAs:@"test"];
[manager removeSocketWithLabel:@"test"];
[manager removeSocketWithLabel:@"test"];
}
@end
+20 -26
View File
@@ -10,25 +10,24 @@ import XCTest
@testable import SocketIO
class SocketParserTest: XCTestCase {
let testSocket = SocketIOClient(socketURL: URL(string: "http://localhost/")!)
let testSocket = SocketIOClient(socketURL: NSURL())
//Format key: message; namespace-data-binary-id
static let packetTypes: [String: (String, [Any], [Data], Int)] = [
static let packetTypes: [String: (String, [AnyObject], [NSData], Int)] = [
"0": ("/", [], [], -1), "1": ("/", [], [], -1),
"25[\"test\"]": ("/", ["test"], [], 5),
"2[\"test\",\"~~0\"]": ("/", ["test", "~~0"], [], -1),
"2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]": ("/swift", ["testArrayEmitReturn", ["test3", "test4"] as NSArray], [], -1),
"51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", ["testMultipleItemsWithBufferEmitReturn", [1, 2] as NSArray, ["test": "bob"] as NSDictionary, 25, "polo", ["_placeholder": true, "num": 0] as NSDictionary], [], -1),
"3/swift,0[[\"test3\",\"test4\"]]": ("/swift", [["test3", "test4"] as NSArray], [], 0),
"2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]": ("/swift", ["testArrayEmitReturn", ["test3", "test4"]], [], -1),
"51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", ["testMultipleItemsWithBufferEmitReturn", [1, 2], ["test": "bob"], 25, "polo", ["_placeholder": true, "num": 0]], [], -1),
"3/swift,0[[\"test3\",\"test4\"]]": ("/swift", [["test3", "test4"]], [], 0),
"61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]":
("/swift", [ [1, 2] as NSArray, ["test": "bob"] as NSDictionary, 25, "polo", ["_placeholder": true, "num": 0] as NSDictionary], [], 19),
("/swift", [ [1, 2], ["test": "bob"], 25, "polo", ["_placeholder": true, "num": 0]], [], 19),
"4/swift,": ("/swift", [], [], -1),
"0/swift": ("/swift", [], [], -1),
"1/swift": ("/swift", [], [], -1),
"4\"ERROR\"": ("/", ["ERROR"], [], -1),
"4{\"test\":2}": ("/", [["test": 2]], [], -1),
"41": ("/", [1], [], -1),
"4[1, \"hello\"]": ("/", [1, "hello"], [], -1)]
"41": ("/", [1], [], -1)]
func testDisconnect() {
let message = "1"
@@ -100,38 +99,33 @@ class SocketParserTest: XCTestCase {
validateParseResult(message)
}
func testErrorTypeArray() {
let message = "4[1, \"hello\"]"
validateParseResult(message)
}
func testInvalidInput() {
let message = "8"
switch testSocket.parseString(message) {
case .left(_):
case .Left(_):
return
case .right(_):
case .Right(_):
XCTFail("Created packet when shouldn't have")
}
}
func testGenericParser() {
var parser = SocketStringReader(message: "61-/swift,")
XCTAssertEqual(parser.read(count: 1), "6")
XCTAssertEqual(parser.read(1), "6")
XCTAssertEqual(parser.currentCharacter, "1")
XCTAssertEqual(parser.readUntilOccurence(of: "-"), "1")
XCTAssertEqual(parser.readUntilStringOccurence("-"), "1")
XCTAssertEqual(parser.currentCharacter, "/")
}
func validateParseResult(_ message: String) {
func validateParseResult(message: String) {
let validValues = SocketParserTest.packetTypes[message]!
let packet = testSocket.parseString(message)
let type = String(message.characters.prefix(1))
if case let .right(packet) = packet {
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)
XCTAssertTrue((packet.data as NSArray).isEqual(to: validValues.1), "\(packet.data)")
XCTAssertTrue((packet.binary as NSArray).isEqual(to: validValues.2), "\(packet.binary)")
XCTAssertTrue((packet.data as NSArray).isEqualToArray(validValues.1), "\(packet.data)")
XCTAssertTrue((packet.binary as NSArray).isEqualToArray(validValues.2), "\(packet.binary)")
XCTAssertEqual(packet.id, validValues.3)
} else {
XCTFail()
@@ -140,10 +134,10 @@ class SocketParserTest: XCTestCase {
func testParsePerformance() {
let keys = Array(SocketParserTest.packetTypes.keys)
measure {
for item in keys.enumerated() {
_ = self.testSocket.parseString(item.element)
measureBlock({
for item in keys.enumerate() {
self.testSocket.parseString(item.element)
}
}
})
}
}
+40 -40
View File
@@ -10,13 +10,13 @@ import XCTest
@testable import SocketIO
class SocketSideEffectTest: XCTestCase {
let data = "test".data(using: String.Encoding.utf8)!
let data2 = "test2".data(using: String.Encoding.utf8)!
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
private var socket: SocketIOClient!
override func setUp() {
super.setUp()
socket = SocketIOClient(socketURL: URL(string: "http://localhost/")!)
socket = SocketIOClient(socketURL: NSURL())
socket.setTestable()
}
@@ -25,72 +25,72 @@ class SocketSideEffectTest: XCTestCase {
}
func testFirstAck() {
socket.emitWithAck("test")(0) {data in}
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
XCTAssertEqual(socket.currentAck, 0)
}
func testSecondAck() {
socket.emitWithAck("test")(0) {data in}
socket.emitWithAck("test")(0) {data in}
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
XCTAssertEqual(socket.currentAck, 1)
}
func testHandleAck() {
let expect = expectation(description: "handled ack")
socket.emitWithAck("test")(0) {data in
let expectation = expectationWithDescription("handled ack")
socket.emitWithAck("test")(timeoutAfter: 0) {data in
XCTAssertEqual(data[0] as? String, "hello world")
expect.fulfill()
expectation.fulfill()
}
socket.parseSocketMessage("30[\"hello world\"]")
waitForExpectations(timeout: 3, handler: nil)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleAck2() {
let expect = expectation(description: "handled ack2")
socket.emitWithAck("test")(0) {data in
let expectation = expectationWithDescription("handled ack2")
socket.emitWithAck("test")(timeoutAfter: 0) {data in
XCTAssertTrue(data.count == 2, "Wrong number of ack items")
expect.fulfill()
expectation.fulfill()
}
socket.parseSocketMessage("61-0[{\"_placeholder\":true,\"num\":0},{\"test\":true}]")
socket.parseBinaryData(Data())
waitForExpectations(timeout: 3, handler: nil)
socket.parseBinaryData(NSData())
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleEvent() {
let expect = expectation(description: "handled event")
let expectation = expectationWithDescription("handled event")
socket.on("test") {data, ack in
XCTAssertEqual(data[0] as? String, "hello world")
expect.fulfill()
expectation.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"hello world\"]")
waitForExpectations(timeout: 3, handler: nil)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleStringEventWithQuotes() {
let expect = expectation(description: "handled event")
let expectation = expectationWithDescription("handled event")
socket.on("test") {data, ack in
XCTAssertEqual(data[0] as? String, "\"hello world\"")
expect.fulfill()
expectation.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"\\\"hello world\\\"\"]")
waitForExpectations(timeout: 3, handler: nil)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleOnceEvent() {
let expect = expectation(description: "handled event")
let expectation = expectationWithDescription("handled event")
socket.once("test") {data, ack in
XCTAssertEqual(data[0] as? String, "hello world")
XCTAssertEqual(self.socket.testHandlers.count, 0)
expect.fulfill()
expectation.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"hello world\"]")
waitForExpectations(timeout: 3, handler: nil)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testOffWithEvent() {
@@ -112,46 +112,46 @@ class SocketSideEffectTest: XCTestCase {
}
func testHandlesErrorPacket() {
let expect = expectation(description: "Handled error")
let expectation = expectationWithDescription("Handled error")
socket.on("error") {data, ack in
if let error = data[0] as? String, error == "test error" {
expect.fulfill()
if let error = data[0] as? String where error == "test error" {
expectation.fulfill()
}
}
socket.parseSocketMessage("4\"test error\"")
waitForExpectations(timeout: 3, handler: nil)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleBinaryEvent() {
let expect = expectation(description: "handled binary event")
let expectation = expectationWithDescription("handled binary event")
socket.on("test") {data, ack in
if let dict = data[0] as? NSDictionary, let data = dict["test"] as? NSData {
XCTAssertEqual(data as Data, self.data)
expect.fulfill()
if let dict = data[0] as? NSDictionary, data = dict["test"] as? NSData {
XCTAssertEqual(data, self.data)
expectation.fulfill()
}
}
socket.parseSocketMessage("51-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0}}]")
socket.parseBinaryData(data)
waitForExpectations(timeout: 3, handler: nil)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleMultipleBinaryEvent() {
let expect = expectation(description: "handled multiple binary event")
let expectation = expectationWithDescription("handled multiple binary event")
socket.on("test") {data, ack in
if let dict = data[0] as? NSDictionary, let data = dict["test"] as? NSData,
let data2 = dict["test2"] as? NSData {
XCTAssertEqual(data as Data, self.data)
XCTAssertEqual(data2 as Data, self.data2)
expect.fulfill()
if let dict = data[0] as? NSDictionary, data = dict["test"] as? NSData,
data2 = dict["test2"] as? NSData {
XCTAssertEqual(data, self.data)
XCTAssertEqual(data2, self.data2)
expectation.fulfill()
}
}
socket.parseSocketMessage("52-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0},\"test2\":{\"_placeholder\":true,\"num\":1}}]")
socket.parseBinaryData(data)
socket.parseBinaryData(data2)
waitForExpectations(timeout: 3, handler: nil)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testSocketManager() {
+34 -33
View File
@@ -24,8 +24,8 @@ import Foundation
import Security
public class SSLCert : NSObject {
var certData: Data?
var key: SecKey?
var certData: NSData?
var key: SecKeyRef?
/**
Designated init for certificates
@@ -34,7 +34,7 @@ public class SSLCert : NSObject {
- returns: a representation security object to be used with
*/
public init(data: Data) {
public init(data: NSData) {
self.certData = data
}
@@ -45,7 +45,7 @@ public class SSLCert : NSObject {
- returns: a representation security object to be used with
*/
public init(key: SecKey) {
public init(key: SecKeyRef) {
self.key = key
}
}
@@ -54,8 +54,8 @@ public class SSLSecurity : NSObject {
public var validatedDN = true //should the domain name be validated?
var isReady = false //is the key processing done?
var certificates: [Data]? //the certificates
@nonobjc var pubKeys: [SecKey]? //the public keys
var certificates: [NSData]? //the certificates
@nonobjc var pubKeys: [SecKeyRef]? //the public keys
var usePublicKeys = false //use public keys or certificate validation?
/**
@@ -66,12 +66,12 @@ public class SSLSecurity : NSObject {
- returns: a representation security object to be used with
*/
public convenience init(usePublicKeys: Bool = false) {
let paths = Bundle.main.paths(forResourcesOfType: "cer", inDirectory: ".")
let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".")
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 as Data))
certs.append(SSLCert(data: data))
}
return certs
}
@@ -93,10 +93,10 @@ public class SSLSecurity : NSObject {
super.init()
if self.usePublicKeys {
DispatchQueue.global(qos: .default).async {
let pubKeys = certs.reduce([SecKey]()) { (pubKeys: [SecKey], cert: SSLCert) -> [SecKey] in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) {
let pubKeys = certs.reduce([SecKeyRef]()) { (pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in
var pubKeys = pubKeys
if let data = cert.certData, cert.key == nil {
if let data = cert.certData where cert.key == nil {
cert.key = self.extractPublicKey(data)
}
if let key = cert.key {
@@ -109,7 +109,7 @@ public class SSLSecurity : NSObject {
self.isReady = true
}
} else {
let certificates = certs.reduce([Data]()) { (certificates: [Data], cert: SSLCert) -> [Data] in
let certificates = certs.reduce([NSData]()) { (certificates: [NSData], cert: SSLCert) -> [NSData] in
var certificates = certificates
if let data = cert.certData {
certificates.append(data)
@@ -129,26 +129,26 @@ public class SSLSecurity : NSObject {
- returns: if the key was successfully validated
*/
public func isValid(_ trust: SecTrust, domain: String?) -> Bool {
public func isValid(trust: SecTrustRef, domain: String?) -> Bool {
var tries = 0
while !self.isReady {
while(!self.isReady) {
usleep(1000)
tries += 1
if tries > 5 {
return false //doesn't appear it is going to ever be ready...
}
}
var policy: SecPolicy
var policy: SecPolicyRef
if self.validatedDN {
policy = SecPolicyCreateSSL(true, domain as NSString?)
policy = SecPolicyCreateSSL(true, domain)
} else {
policy = SecPolicyCreateBasicX509()
}
SecTrustSetPolicies(trust,policy)
if self.usePublicKeys {
if let keys = self.pubKeys {
let serverPubKeys = publicKeyChain(trust)
let serverPubKeys = publicKeyChainForTrust(trust)
for serverKey in serverPubKeys as [AnyObject] {
for key in keys as [AnyObject] {
if serverKey.isEqual(key) {
@@ -158,15 +158,15 @@ public class SSLSecurity : NSObject {
}
}
} else if let certs = self.certificates {
let serverCerts = certificateChain(trust)
let serverCerts = certificateChainForTrust(trust)
var collect = [SecCertificate]()
for cert in certs {
collect.append(SecCertificateCreateWithData(nil,cert as CFData)!)
collect.append(SecCertificateCreateWithData(nil,cert)!)
}
SecTrustSetAnchorCertificates(trust,collect as NSArray)
var result: SecTrustResultType = .unspecified
SecTrustSetAnchorCertificates(trust,collect)
var result = SecTrustResultType.Invalid
SecTrustEvaluate(trust,&result)
if result == .unspecified || result == .proceed {
if result == .Unspecified || result == .Proceed {
var trustedCount = 0
for serverCert in serverCerts {
for cert in certs {
@@ -191,10 +191,10 @@ public class SSLSecurity : NSObject {
- returns: a public key
*/
func extractPublicKey(_ data: Data) -> SecKey? {
guard let cert = SecCertificateCreateWithData(nil, data as CFData) else { return nil }
func extractPublicKey(data: NSData) -> SecKeyRef? {
guard let cert = SecCertificateCreateWithData(nil, data) else { return nil }
return extractPublicKey(cert, policy: SecPolicyCreateBasicX509())
return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509())
}
/**
@@ -204,12 +204,13 @@ public class SSLSecurity : NSObject {
- returns: a public key
*/
func extractPublicKey(_ cert: SecCertificate, policy: SecPolicy) -> SecKey? {
func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? {
var possibleTrust: SecTrust?
SecTrustCreateWithCertificates(cert, policy, &possibleTrust)
guard let trust = possibleTrust else { return nil }
var result: SecTrustResultType = .unspecified
var result = SecTrustResultType.Invalid
SecTrustEvaluate(trust, &result)
return SecTrustCopyPublicKey(trust)
}
@@ -221,11 +222,11 @@ public class SSLSecurity : NSObject {
- returns: the certificate chain for the trust
*/
func certificateChain(_ trust: SecTrust) -> [Data] {
let certificates = (0..<SecTrustGetCertificateCount(trust)).reduce([Data]()) { (certificates: [Data], index: Int) -> [Data] in
func certificateChainForTrust(trust: SecTrustRef) -> [NSData] {
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!) as Data)
certificates.append(SecCertificateCopyData(cert!))
return certificates
}
@@ -239,12 +240,12 @@ public class SSLSecurity : NSObject {
- returns: the public keys from the certifcate chain for the trust
*/
@nonobjc func publicKeyChain(_ trust: SecTrust) -> [SecKey] {
@nonobjc func publicKeyChainForTrust(trust: SecTrustRef) -> [SecKeyRef] {
let policy = SecPolicyCreateBasicX509()
let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKey]()) { (keys: [SecKey], index: Int) -> [SecKey] 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 = extractPublicKey(cert!, policy: policy) {
if let key = extractPublicKeyFromCert(cert!, policy: policy) {
keys.append(key)
}
+4 -4
View File
@@ -33,15 +33,15 @@ public final class SocketAckEmitter : NSObject {
self.ackNum = ackNum
}
public func with(_ items: SocketData...) {
public func with(items: AnyObject...) {
guard ackNum != -1 else { return }
socket.emitAck(ackNum, with: items)
socket.emitAck(ackNum, withItems: items)
}
public func with(_ items: [Any]) {
public func with(items: [AnyObject]) {
guard ackNum != -1 else { return }
socket.emitAck(ackNum, with: items)
socket.emitAck(ackNum, withItems: items)
}
}
+12 -8
View File
@@ -35,7 +35,7 @@ private struct SocketAck : Hashable {
self.ack = ack
}
init(ack: Int, callback: @escaping AckCallback) {
init(ack: Int, callback: AckCallback) {
self.ack = ack
self.callback = callback
}
@@ -52,21 +52,25 @@ private func ==(lhs: SocketAck, rhs: SocketAck) -> Bool {
struct SocketAckManager {
private var acks = Set<SocketAck>(minimumCapacity: 1)
mutating func addAck(_ ack: Int, callback: @escaping AckCallback) {
mutating func addAck(ack: Int, callback: AckCallback) {
acks.insert(SocketAck(ack: ack, callback: callback))
}
/// Should be called on handle queue
mutating func executeAck(_ ack: Int, with items: [Any], onQueue: DispatchQueue) {
let ack = acks.remove(SocketAck(ack: ack))
mutating func executeAck(ack: Int, items: [AnyObject], onQueue: dispatch_queue_t) {
let callback = acks.remove(SocketAck(ack: ack))
onQueue.async() { ack?.callback(items) }
dispatch_async(onQueue) {
callback?.callback(items)
}
}
/// Should be called on handle queue
mutating func timeoutAck(_ ack: Int, onQueue: DispatchQueue) {
let ack = acks.remove(SocketAck(ack: ack))
mutating func timeoutAck(ack: Int, onQueue: dispatch_queue_t) {
let callback = acks.remove(SocketAck(ack: ack))
onQueue.async() { ack?.callback?(["NO ACK"]) }
dispatch_async(onQueue) {
callback?.callback(["NO ACK"])
}
}
}
+2 -2
View File
@@ -26,12 +26,12 @@ import Foundation
public final class SocketAnyEvent : NSObject {
public let event: String
public let items: [Any]?
public let items: NSArray?
override public var description: String {
return "SocketAnyEvent: Event: \(event) items: \(items ?? nil)"
}
init(event: String, items: [Any]?) {
init(event: String, items: NSArray?) {
self.event = event
self.items = items
}
+9 -9
View File
@@ -43,12 +43,12 @@ import Foundation
manager["room1"]?.emit("hello")
```
*/
open class SocketClientManager : NSObject {
open static let sharedManager = SocketClientManager()
public final class SocketClientManager : NSObject {
public static let sharedManager = SocketClientManager()
private var sockets = [String: SocketIOClient]()
open subscript(string: String) -> SocketIOClient? {
public subscript(string: String) -> SocketIOClient? {
get {
return sockets[string]
}
@@ -58,25 +58,25 @@ open class SocketClientManager : NSObject {
}
}
open func addSocket(_ socket: SocketIOClient, labeledAs label: String) {
public func addSocket(socket: SocketIOClient, labeledAs label: String) {
sockets[label] = socket
}
open func removeSocket(withLabel label: String) -> SocketIOClient? {
return sockets.removeValue(forKey: label)
public func removeSocket(withLabel label: String) -> SocketIOClient? {
return sockets.removeValueForKey(label)
}
open func removeSocket(_ socket: SocketIOClient) -> SocketIOClient? {
public func removeSocket(socket: SocketIOClient) -> SocketIOClient? {
var returnSocket: SocketIOClient?
for (label, dictSocket) in sockets where dictSocket === socket {
returnSocket = sockets.removeValue(forKey: label)
returnSocket = sockets.removeValueForKey(label)
}
return returnSocket
}
open func removeSockets() {
public func removeSockets() {
sockets.removeAll()
}
}
+184 -182
View File
@@ -24,24 +24,24 @@
import Foundation
public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, SocketEngineWebsocket {
public let emitQueue = DispatchQueue(label: "com.socketio.engineEmitQueue", attributes: [])
public let handleQueue = DispatchQueue(label: "com.socketio.engineHandleQueue", attributes: [])
public let parseQueue = DispatchQueue(label: "com.socketio.engineParseQueue", attributes: [])
public final class SocketEngine : NSObject, NSURLSessionDelegate, 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)
public var connectParams: [String: Any]? {
public var connectParams: [String: AnyObject]? {
didSet {
(urlPolling, urlWebSocket) = createURLs()
}
}
public var postWait = [String]()
public var waitingForPoll = false
public var waitingForPost = false
public private(set) var closed = false
public private(set) var connected = false
public private(set) var cookies: [HTTPCookie]?
public private(set) var cookies: [NSHTTPCookie]?
public private(set) var doubleEncodeUTF8 = true
public private(set) var extraHeaders: [String: String]?
public private(set) var fastUpgrade = false
@@ -50,28 +50,28 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
public private(set) var invalidated = false
public private(set) var polling = true
public private(set) var probing = false
public private(set) var session: URLSession?
public private(set) var session: NSURLSession?
public private(set) var sid = ""
public private(set) var socketPath = "/engine.io/"
public private(set) var urlPolling = URL(string: "http://localhost/")!
public private(set) var urlWebSocket = URL(string: "http://localhost/")!
public private(set) var urlPolling = NSURL()
public private(set) var urlWebSocket = NSURL()
public private(set) var websocket = false
public private(set) var ws: WebSocket?
public weak var client: SocketEngineClient?
private weak var sessionDelegate: URLSessionDelegate?
private weak var sessionDelegate: NSURLSessionDelegate?
private let logType = "SocketEngine"
private let url: URL
private let url: NSURL
private var pingInterval: Double?
private var pingTimeout = 0.0 {
didSet {
pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25))
}
}
private var pongsMissed = 0
private var pongsMissedMax = 0
private var probeWait = ProbeWaitQueue()
@@ -80,44 +80,45 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
private var selfSigned = false
private var voipEnabled = false
public init(client: SocketEngineClient, url: URL, config: SocketIOClientConfiguration) {
public init(client: SocketEngineClient, url: NSURL, config: SocketIOClientConfiguration) {
self.client = client
self.url = url
for option in config {
switch option {
case let .connectParams(params):
case let .ConnectParams(params):
connectParams = params
case let .cookies(cookies):
case let .Cookies(cookies):
self.cookies = cookies
case let .doubleEncodeUTF8(encode):
case let .DoubleEncodeUTF8(encode):
doubleEncodeUTF8 = encode
case let .extraHeaders(headers):
case let .ExtraHeaders(headers):
extraHeaders = headers
case let .sessionDelegate(delegate):
case let .SessionDelegate(delegate):
sessionDelegate = delegate
case let .forcePolling(force):
case let .ForcePolling(force):
forcePolling = force
case let .forceWebsockets(force):
case let .ForceWebsockets(force):
forceWebsockets = force
case let .path(path):
case let .Path(path):
socketPath = path
if !socketPath.hasSuffix("/") {
socketPath += "/"
}
case let .voipEnabled(enable):
case let .VoipEnabled(enable):
voipEnabled = enable
case let .secure(secure):
case let .Secure(secure):
self.secure = secure
case let .selfSigned(selfSigned):
self.selfSigned = selfSigned
case let .security(security):
case let .Security(security):
self.security = security
case let .SelfSigned(selfSigned):
self.selfSigned = selfSigned
default:
continue
}
}
super.init()
sessionDelegate = sessionDelegate ?? self
@@ -125,17 +126,17 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
(urlPolling, urlWebSocket) = createURLs()
}
public convenience init(client: SocketEngineClient, url: URL, options: NSDictionary?) {
public convenience init(client: SocketEngineClient, url: NSURL, options: NSDictionary?) {
self.init(client: client, url: url, config: options?.toSocketConfiguration() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Engine is being released", type: logType)
closed = true
stopPolling()
}
private func checkAndHandleEngineError(_ msg: String) {
private func checkAndHandleEngineError(msg: String) {
do {
let dict = try msg.toNSDictionary()
guard let error = dict["message"] as? String else { return }
@@ -146,74 +147,74 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
2: Bad handshake request
3: Bad request
*/
didError(reason: error)
didError(error)
} catch {
client?.engineDidError(reason: "Got unknown error from server \(msg)")
client?.engineDidError("Got unknown error from server \(msg)")
}
}
private func handleBase64(message: String) {
// binary in base64 string
let noPrefix = message[message.index(message.startIndex, offsetBy: 2)..<message.endIndex]
let noPrefix = message[message.startIndex.advancedBy(2)..<message.endIndex]
if let data = NSData(base64Encoded: noPrefix, options: .ignoreUnknownCharacters) {
client?.parseEngineBinaryData(data as Data)
if let data = NSData(base64EncodedString: noPrefix, options: .IgnoreUnknownCharacters) {
client?.parseEngineBinaryData(data)
}
}
private func closeOutEngine(reason: String) {
sid = ""
closed = true
invalidated = true
connected = false
ws?.disconnect()
stopPolling()
client?.engineDidClose(reason: reason)
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(reason: "reconnect")
disconnect("reconnect")
}
DefaultSocketLogger.Logger.log("Starting engine. Server: %@", type: logType, args: url)
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
resetEngine()
if forceWebsockets {
polling = false
websocket = true
createWebsocketAndConnect()
return
}
let reqPolling = NSMutableURLRequest(url: urlPolling)
let reqPolling = NSMutableURLRequest(URL: urlPolling)
if cookies != nil {
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doLongPoll(for: reqPolling as URLRequest)
doLongPoll(reqPolling)
}
private func createURLs() -> (URL, URL) {
private func createURLs() -> (NSURL, NSURL) {
if client == nil {
return (URL(string: "http://localhost/")!, URL(string: "http://localhost/")!)
return (NSURL(), NSURL())
}
var urlPolling = URLComponents(string: url.absoluteString)!
var urlWebSocket = URLComponents(string: url.absoluteString)!
let urlPolling = NSURLComponents(URL: url, resolvingAgainstBaseURL: true)!
let urlWebSocket = NSURLComponents(URL: url, resolvingAgainstBaseURL: true)!
var queryString = ""
urlWebSocket.path = socketPath
@@ -238,15 +239,15 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
urlWebSocket.percentEncodedQuery = "transport=websocket" + queryString
urlPolling.percentEncodedQuery = "transport=polling&b64=1" + queryString
return (urlPolling.url!, urlWebSocket.url!)
return (urlPolling.URL!, urlWebSocket.URL!)
}
private func createWebsocketAndConnect() {
ws = WebSocket(url: urlWebSocketWithSid as URL)
ws = WebSocket(url: urlWebSocketWithSid)
if cookies != nil {
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
for (key, value) in headers {
ws?.headers[key] = value
}
@@ -261,43 +262,43 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
ws?.callbackQueue = handleQueue
ws?.voipEnabled = voipEnabled
ws?.delegate = self
ws?.disableSSLCertValidation = selfSigned
ws?.selfSignedSSL = selfSigned
ws?.security = security
ws?.connect()
}
public func didError(reason: String) {
DefaultSocketLogger.Logger.error("%@", type: logType, args: reason)
client?.engineDidError(reason: reason)
disconnect(reason: reason)
public func didError(error: String) {
DefaultSocketLogger.Logger.error("%@", type: logType, args: error)
client?.engineDidError(error)
disconnect(error)
}
public func disconnect(reason: String) {
guard connected else { return closeOutEngine(reason: reason) }
guard connected else { return closeOutEngine(reason) }
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
if closed {
return closeOutEngine(reason: reason)
return closeOutEngine(reason)
}
if websocket {
sendWebSocketMessage("", withType: .close, withData: [])
closeOutEngine(reason: reason)
sendWebSocketMessage("", withType: .Close, withData: [])
closeOutEngine(reason)
} else {
disconnectPolling(reason: reason)
disconnectPolling(reason)
}
}
// 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
private func disconnectPolling(reason: String) {
emitQueue.sync {
self.postWait.append(String(SocketEnginePacketType.close.rawValue))
dispatch_sync(emitQueue) {
self.postWait.append(String(SocketEnginePacketType.Close.rawValue))
let req = self.createRequestForPostWithPostWait()
self.doRequest(for: req) {_, _, _ in }
self.closeOutEngine(reason: reason)
self.doRequest(req) {_, _, _ in }
self.closeOutEngine(reason)
}
}
@@ -307,7 +308,7 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
"we'll probably disconnect soon. You should report this.", type: logType)
}
sendWebSocketMessage("", withType: .upgrade, withData: [])
sendWebSocketMessage("", withType: .Upgrade, withData: [])
websocket = true
polling = false
fastUpgrade = false
@@ -318,108 +319,105 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
private func flushProbeWait() {
DefaultSocketLogger.Logger.log("Flushing probe wait", type: logType)
emitQueue.async {
dispatch_async(emitQueue) {
for waiter in self.probeWait {
self.write(waiter.msg, withType: waiter.type, withData: waiter.data)
}
self.probeWait.removeAll(keepingCapacity: false)
self.probeWait.removeAll(keepCapacity: false)
if self.postWait.count != 0 {
self.flushWaitingForPostToWebSocket()
}
}
}
// We had packets waiting for send when we upgraded
// Send them raw
public func flushWaitingForPostToWebSocket() {
guard let ws = self.ws else { return }
for msg in postWait {
ws.write(string: msg)
ws.writeString(msg)
}
postWait.removeAll(keepingCapacity: false)
postWait.removeAll(keepCapacity: true)
}
private func handleClose(_ reason: String) {
client?.engineDidClose(reason: reason)
private func handleClose(reason: String) {
client?.engineDidClose(reason)
}
private func handleMessage(_ message: String) {
private func handleMessage(message: String) {
client?.parseEngineMessage(message)
}
private func handleNOOP() {
doPoll()
}
private func handleOpen(openData: String) {
guard let json = try? openData.toNSDictionary() else {
didError(reason: "Error parsing open packet")
do {
let json = try openData.toNSDictionary()
guard let sid = json["sid"] as? String else {
client?.engineDidError("Open packet contained no sid")
return
}
return
}
guard let sid = json["sid"] as? String else {
didError(reason: "Open packet contained no sid")
let upgradeWs: Bool
return
self.sid = sid
connected = true
if let upgrades = json["upgrades"] as? [String] {
upgradeWs = upgrades.contains("websocket")
} else {
upgradeWs = false
}
if let pingInterval = json["pingInterval"] as? Double, let pingTimeout = json["pingTimeout"] as? Double {
self.pingInterval = pingInterval / 1000.0
self.pingTimeout = pingTimeout / 1000.0
}
if !forcePolling && !forceWebsockets && upgradeWs {
createWebsocketAndConnect()
}
sendPing()
if !forceWebsockets {
doPoll()
}
client?.engineDidOpen("Connect")
} catch {
didError("Error parsing open packet")
}
let upgradeWs: Bool
self.sid = sid
connected = true
if let upgrades = json["upgrades"] as? [String] {
upgradeWs = upgrades.contains("websocket")
} else {
upgradeWs = false
}
if let pingInterval = json["pingInterval"] as? Double, let pingTimeout = json["pingTimeout"] as? Double {
self.pingInterval = pingInterval / 1000.0
self.pingTimeout = pingTimeout / 1000.0
}
if !forcePolling && !forceWebsockets && upgradeWs {
createWebsocketAndConnect()
}
sendPing()
if !forceWebsockets {
doPoll()
}
client?.engineDidOpen(reason: "Connect")
}
private func handlePong(with message: String) {
private func handlePong(pongMessage: String) {
pongsMissed = 0
// We should upgrade
if message == "3probe" {
if pongMessage == "3probe" {
upgradeTransport()
}
}
public func parseEngineData(_ data: Data) {
public func parseEngineData(data: NSData) {
DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data)
client?.parseEngineBinaryData(data.subdata(in: 1..<data.endIndex))
client?.parseEngineBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
}
public func parseEngineMessage(_ message: String, fromPolling: Bool) {
public func parseEngineMessage(message: String, fromPolling: Bool) {
DefaultSocketLogger.Logger.log("Got message: %@", type: logType, args: message)
let reader = SocketStringReader(message: message)
let fixedString: String
if message.hasPrefix("b4") {
return handleBase64(message: message)
return handleBase64(message)
}
guard let type = SocketEnginePacketType(rawValue: Int(reader.currentCharacter) ?? -1) else {
@@ -428,28 +426,28 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
return
}
if fromPolling && type != .noop && doubleEncodeUTF8 {
if fromPolling && type != .Noop && doubleEncodeUTF8 {
fixedString = fixDoubleUTF8(message)
} else {
fixedString = message
}
switch type {
case .message:
handleMessage(String(fixedString.characters.dropFirst()))
case .noop:
case .Message:
handleMessage(fixedString[fixedString.startIndex.successor()..<fixedString.endIndex])
case .Noop:
handleNOOP()
case .pong:
handlePong(with: fixedString)
case .open:
handleOpen(openData: String(fixedString.characters.dropFirst()))
case .close:
case .Pong:
handlePong(fixedString)
case .Open:
handleOpen(fixedString[fixedString.startIndex.successor()..<fixedString.endIndex])
case .Close:
handleClose(fixedString)
default:
DefaultSocketLogger.Logger.log("Got unknown packet type", type: logType)
}
}
// Puts the engine back in its default state
private func resetEngine() {
closed = false
@@ -458,7 +456,9 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
polling = true
probing = false
invalidated = false
session = Foundation.URLSession(configuration: .default, delegate: sessionDelegate, delegateQueue: OperationQueue.main)
session = NSURLSession(configuration: .defaultSessionConfiguration(),
delegate: sessionDelegate,
delegateQueue: NSOperationQueue.mainQueue())
sid = ""
waitingForPoll = false
waitingForPost = false
@@ -466,40 +466,43 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
}
private func sendPing() {
guard connected else { return }
// Server is not responding
if pongsMissed > pongsMissedMax {
client?.engineDidClose(reason: "Ping timeout")
if !connected {
return
}
guard let pingInterval = pingInterval else { return }
pongsMissed += 1
write("", withType: .ping, withData: [])
//Server is not responding
if pongsMissed > pongsMissedMax {
client?.engineDidClose("Ping timeout")
return
}
let time = DispatchTime.now() + Double(Int64(pingInterval * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {[weak self] in self?.sendPing() }
if let pingInterval = pingInterval {
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)
fastUpgrade = true
sendPollMessage("", withType: .noop, withData: [])
sendPollMessage("", withType: .Noop, withData: [])
// After this point, we should not send anymore polling messages
}
}
/// Write a message, independent of transport.
public func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data]) {
emitQueue.async {
public func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData]) {
dispatch_async(emitQueue) {
guard self.connected else { return }
if self.websocket {
DefaultSocketLogger.Logger.log("Writing ws: %@ has data: %@",
type: self.logType, args: msg, data.count != 0)
@@ -513,7 +516,7 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
}
}
}
// Delegate methods
public func websocketDidConnect(socket: WebSocket) {
if !forceWebsockets {
@@ -525,24 +528,23 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
polling = false
}
}
public func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
probing = false
if closed {
client?.engineDidClose(reason: "Disconnect")
client?.engineDidClose("Disconnect")
return
}
if websocket {
connected = false
websocket = false
if let reason = error?.localizedDescription {
didError(reason: reason)
didError(reason)
} else {
client?.engineDidClose(reason: "Socket Disconnected")
client?.engineDidClose("Socket Disconnected")
}
} else {
flushProbeWait()
@@ -551,9 +553,9 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
}
extension SocketEngine {
public func URLSession(session: URLSession, didBecomeInvalidWithError error: NSError?) {
public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
DefaultSocketLogger.Logger.error("Engine URLSession became invalid", type: "SocketEngine")
didError(reason: "Engine URLSession became invalid")
didError("Engine URLSession became invalid")
}
}
+2 -2
View File
@@ -29,6 +29,6 @@ import Foundation
func engineDidError(reason: String)
func engineDidClose(reason: String)
func engineDidOpen(reason: String)
func parseEngineMessage(_ msg: String)
func parseEngineBinaryData(_ data: Data)
func parseEngineMessage(msg: String)
func parseEngineBinaryData(data: NSData)
}
+1 -1
View File
@@ -26,5 +26,5 @@
import Foundation
@objc public enum SocketEnginePacketType : Int {
case open, close, ping, pong, message, upgrade, noop
case Open, Close, Ping, Pong, Message, Upgrade, Noop
}
+39 -42
View File
@@ -30,7 +30,7 @@ public protocol SocketEnginePollable : SocketEngineSpec {
/// Holds strings waiting to be sent over polling.
/// You shouldn't need to mess with this.
var postWait: [String] { get set }
var session: URLSession? { get }
var session: NSURLSession? { get }
/// Because socket.io doesn't let you send two polling request at the same time
/// we have to keep track if there's an outstanding poll
var waitingForPoll: Bool { get set }
@@ -39,17 +39,15 @@ public protocol SocketEnginePollable : SocketEngineSpec {
var waitingForPost: Bool { get set }
func doPoll()
func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data])
func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData])
func stopPolling()
}
// Default polling methods
extension SocketEnginePollable {
private func addHeaders(for req: URLRequest) -> URLRequest {
var req = req
private func addHeaders(req: NSMutableURLRequest) {
if cookies != nil {
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
req.allHTTPHeaderFields = headers
}
@@ -58,12 +56,10 @@ extension SocketEnginePollable {
req.setValue(value, forHTTPHeaderField: headerName)
}
}
return req
}
func createRequestForPostWithPostWait() -> URLRequest {
defer { postWait.removeAll(keepingCapacity: true) }
func createRequestForPostWithPostWait() -> NSURLRequest {
defer { postWait.removeAll(keepCapacity: true) }
var postStr = ""
@@ -75,52 +71,49 @@ extension SocketEnginePollable {
DefaultSocketLogger.Logger.log("Created POST string: %@", type: "SocketEnginePolling", args: postStr)
var req = URLRequest(url: urlPollingWithSid)
let postData = postStr.data(using: .utf8, allowLossyConversion: false)!
let req = NSMutableURLRequest(URL: urlPollingWithSid)
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
req = addHeaders(for: req)
addHeaders(req)
req.httpMethod = "POST"
req.HTTPMethod = "POST"
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
req.httpBody = postData
req.setValue(String(postData.count), forHTTPHeaderField: "Content-Length")
req.HTTPBody = postData
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
return req as URLRequest
return req
}
public func doPoll() {
if websocket || waitingForPoll || !connected || closed {
return
}
if websocket || waitingForPoll || !connected || closed { return }
waitingForPoll = true
var req = URLRequest(url: urlPollingWithSid)
let req = NSMutableURLRequest(URL: urlPollingWithSid)
req = addHeaders(for: req)
doLongPoll(for: req )
addHeaders(req)
doLongPoll(req)
}
func doRequest(for req: URLRequest, callbackWith callback: @escaping (Data?, URLResponse?, Error?) -> Void) {
func doRequest(req: NSURLRequest, withCallback callback: (NSData?, NSURLResponse?, NSError?) -> Void) {
if !polling || closed || invalidated || fastUpgrade {
return
}
DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling")
session?.dataTask(with: req, completionHandler: callback).resume()
session?.dataTaskWithRequest(req, completionHandler: callback).resume()
}
func doLongPoll(for req: URLRequest) {
doRequest(for: req) {[weak self] data, res, err in
guard let this = self, this.polling else { return }
func doLongPoll(req: NSURLRequest) {
doRequest(req) {[weak self] data, res, err in
guard let this = self where this.polling else { return }
if err != nil || data == nil {
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
if this.polling {
this.didError(reason: err?.localizedDescription ?? "Error")
this.didError(err?.localizedDescription ?? "Error")
}
return
@@ -128,8 +121,8 @@ extension SocketEnginePollable {
DefaultSocketLogger.Logger.log("Got polling response", type: "SocketEnginePolling")
if let str = String(data: data!, encoding: String.Encoding.utf8) {
this.parseQueue.async {
if let str = String(data: data!, encoding: NSUTF8StringEncoding) {
dispatch_async(this.parseQueue) {
this.parsePollingMessage(str)
}
}
@@ -158,14 +151,14 @@ extension SocketEnginePollable {
DefaultSocketLogger.Logger.log("POSTing", type: "SocketEnginePolling")
doRequest(for: req) {[weak self] data, res, err in
doRequest(req) {[weak self] data, res, err in
guard let this = self else { return }
if err != nil {
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
if this.polling {
this.didError(reason: err?.localizedDescription ?? "Error")
this.didError(err?.localizedDescription ?? "Error")
}
return
@@ -173,7 +166,7 @@ extension SocketEnginePollable {
this.waitingForPost = false
this.emitQueue.async {
dispatch_async(this.emitQueue) {
if !this.fastUpgrade {
this.flushWaitingForPost()
this.doPoll()
@@ -182,18 +175,22 @@ extension SocketEnginePollable {
}
}
func parsePollingMessage(_ str: String) {
func parsePollingMessage(str: String) {
guard str.characters.count != 1 else { return }
var reader = SocketStringReader(message: str)
while reader.hasNext {
if let n = Int(reader.readUntilOccurence(of: ":")) {
let str = reader.read(count: n)
if let n = Int(reader.readUntilStringOccurence(":")) {
let str = reader.read(n)
handleQueue.async { self.parseEngineMessage(str, fromPolling: true) }
dispatch_async(handleQueue) {
self.parseEngineMessage(str, fromPolling: true)
}
} else {
handleQueue.async { self.parseEngineMessage(str, fromPolling: true) }
dispatch_async(handleQueue) {
self.parseEngineMessage(str, fromPolling: true)
}
break
}
}
@@ -201,7 +198,7 @@ extension SocketEnginePollable {
/// Send polling message.
/// Only call on emitQueue
public func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data]) {
public func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData]) {
DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue)
let fixedMessage: String
@@ -214,7 +211,7 @@ extension SocketEnginePollable {
postWait.append(String(type.rawValue) + fixedMessage)
for data in datas {
if case let .right(bin) = createBinaryDataForSend(using: data) {
if case let .Right(bin) = createBinaryDataForSend(data) {
postWait.append(bin)
}
}
+32 -32
View File
@@ -29,79 +29,79 @@ import Foundation
weak var client: SocketEngineClient? { get set }
var closed: Bool { get }
var connected: Bool { get }
var connectParams: [String: Any]? { get set }
var connectParams: [String: AnyObject]? { get set }
var doubleEncodeUTF8: Bool { get }
var cookies: [HTTPCookie]? { get }
var cookies: [NSHTTPCookie]? { get }
var extraHeaders: [String: String]? { get }
var fastUpgrade: Bool { get }
var forcePolling: Bool { get }
var forceWebsockets: Bool { get }
var parseQueue: DispatchQueue { get }
var parseQueue: dispatch_queue_t! { get }
var polling: Bool { get }
var probing: Bool { get }
var emitQueue: DispatchQueue { get }
var handleQueue: DispatchQueue { get }
var emitQueue: dispatch_queue_t! { get }
var handleQueue: dispatch_queue_t! { get }
var sid: String { get }
var socketPath: String { get }
var urlPolling: URL { get }
var urlWebSocket: URL { get }
var urlPolling: NSURL { get }
var urlWebSocket: NSURL { get }
var websocket: Bool { get }
var ws: WebSocket? { get }
init(client: SocketEngineClient, url: URL, options: NSDictionary?)
init(client: SocketEngineClient, url: NSURL, options: NSDictionary?)
func connect()
func didError(reason: String)
func didError(error: String)
func disconnect(reason: String)
func doFastUpgrade()
func flushWaitingForPostToWebSocket()
func parseEngineData(_ data: Data)
func parseEngineMessage(_ message: String, fromPolling: Bool)
func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data])
func parseEngineData(data: NSData)
func parseEngineMessage(message: String, fromPolling: Bool)
func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData])
}
extension SocketEngineSpec {
var urlPollingWithSid: URL {
var com = URLComponents(url: urlPolling, resolvingAgainstBaseURL: false)!
var urlPollingWithSid: NSURL {
let com = NSURLComponents(URL: urlPolling, resolvingAgainstBaseURL: false)!
com.percentEncodedQuery = com.percentEncodedQuery! + "&sid=\(sid.urlEncode()!)"
return com.url!
return com.URL!
}
var urlWebSocketWithSid: URL {
var com = URLComponents(url: urlWebSocket, resolvingAgainstBaseURL: false)!
var urlWebSocketWithSid: NSURL {
let com = NSURLComponents(URL: urlWebSocket, resolvingAgainstBaseURL: false)!
com.percentEncodedQuery = com.percentEncodedQuery! + (sid == "" ? "" : "&sid=\(sid.urlEncode()!)")
return com.url!
return com.URL!
}
func createBinaryDataForSend(using data: Data) -> Either<Data, String> {
func createBinaryDataForSend(data: NSData) -> Either<NSData, String> {
if websocket {
var byteArray = [UInt8](repeating: 0x4, count: 1)
var byteArray = [UInt8](count: 1, repeatedValue: 0x4)
let mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.append(data)
mutData.appendData(data)
return .left(mutData as Data)
return .Left(mutData)
} else {
let str = "b4" + data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
let str = "b4" + data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
return .right(str)
return .Right(str)
}
}
func doubleEncodeUTF8(_ string: String) -> String {
if let latin1 = string.data(using: String.Encoding.utf8),
let utf8 = NSString(data: latin1, encoding: String.Encoding.isoLatin1.rawValue) {
func doubleEncodeUTF8(string: String) -> String {
if let latin1 = string.dataUsingEncoding(NSUTF8StringEncoding),
utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding) {
return utf8 as String
} else {
return string
}
}
func fixDoubleUTF8(_ string: String) -> String {
if let utf8 = string.data(using: String.Encoding.isoLatin1),
let latin1 = NSString(data: utf8, encoding: String.Encoding.utf8.rawValue) {
func fixDoubleUTF8(string: String) -> String {
if let utf8 = string.dataUsingEncoding(NSISOLatin1StringEncoding),
latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding) {
return latin1 as String
} else {
return string
@@ -109,7 +109,7 @@ extension SocketEngineSpec {
}
/// Send an engine message (4)
func send(_ msg: String, withData datas: [Data]) {
write(msg, withType: .message, withData: datas)
func send(msg: String, withData datas: [NSData]) {
write(msg, withType: .Message, withData: datas)
}
}
+12 -12
View File
@@ -27,36 +27,36 @@ import Foundation
/// Protocol that is used to implement socket.io WebSocket support
public protocol SocketEngineWebsocket : SocketEngineSpec, WebSocketDelegate {
func sendWebSocketMessage(_ str: String, withType type: SocketEnginePacketType, withData datas: [Data])
func sendWebSocketMessage(str: String, withType type: SocketEnginePacketType, withData datas: [NSData])
}
// WebSocket methods
extension SocketEngineWebsocket {
func probeWebSocket() {
if ws?.isConnected ?? false {
sendWebSocketMessage("probe", withType: .ping, withData: [])
sendWebSocketMessage("probe", withType: .Ping, withData: [])
}
}
/// Send message on WebSockets
/// Only call on emitQueue
public func sendWebSocketMessage(_ str: String, withType type: SocketEnginePacketType, withData datas: [Data]) {
DefaultSocketLogger.Logger.log("Sending ws: %@ as type: %@", type: "SocketEngine", args: str, type.rawValue)
ws?.write(string: "\(type.rawValue)\(str)")
for data in datas {
if case let .left(bin) = createBinaryDataForSend(using: data) {
ws?.write(data: bin)
public func sendWebSocketMessage(str: String, withType type: SocketEnginePacketType, withData datas: [NSData]) {
DefaultSocketLogger.Logger.log("Sending ws: %@ as type: %@", type: "SocketEngine", args: str, type.rawValue)
ws?.writeString("\(type.rawValue)\(str)")
for data in datas {
if case let .Left(bin) = createBinaryDataForSend(data) {
ws?.writeData(bin)
}
}
}
}
public func websocketDidReceiveMessage(socket: WebSocket, text: String) {
parseEngineMessage(text, fromPolling: false)
}
public func websocketDidReceiveData(socket: WebSocket, data: Data) {
public func websocketDidReceiveData(socket: WebSocket, data: NSData) {
parseEngineData(data)
}
}
+2 -2
View File
@@ -26,10 +26,10 @@ import Foundation
struct SocketEventHandler {
let event: String
let id: UUID
let id: NSUUID
let callback: NormalCallback
func executeCallback(with items: [Any], withAck ack: Int, withSocket socket: SocketIOClient) {
func executeCallback(items: [AnyObject], withAck ack: Int, withSocket socket: SocketIOClient) {
callback(items, SocketAckEmitter(socket: socket, ackNum: ack))
}
}
+39 -39
View File
@@ -24,66 +24,66 @@
import Foundation
enum JSONError : Error {
enum JSONError : ErrorType {
case notArray
case notNSDictionary
}
extension Array {
func toJSON() throws -> Data {
return try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions(rawValue: 0))
extension Array where Element: AnyObject {
func toJSON() throws -> NSData {
return try NSJSONSerialization.dataWithJSONObject(self as NSArray, options: NSJSONWritingOptions(rawValue: 0))
}
}
extension CharacterSet {
static var allowedURLCharacterSet: CharacterSet {
return CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]\" {}").inverted
extension NSCharacterSet {
static var allowedURLCharacterSet: NSCharacterSet {
return NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
}
}
extension NSDictionary {
private static func keyValueToSocketIOClientOption(key: String, value: Any) -> SocketIOClientOption? {
private static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
switch (key, value) {
case let ("connectParams", params as [String: Any]):
return .connectParams(params)
case let ("cookies", cookies as [HTTPCookie]):
return .cookies(cookies)
case let ("connectParams", params as [String: AnyObject]):
return .ConnectParams(params)
case let ("cookies", cookies as [NSHTTPCookie]):
return .Cookies(cookies)
case let ("doubleEncodeUTF8", encode as Bool):
return .doubleEncodeUTF8(encode)
return .DoubleEncodeUTF8(encode)
case let ("extraHeaders", headers as [String: String]):
return .extraHeaders(headers)
return .ExtraHeaders(headers)
case let ("forceNew", force as Bool):
return .forceNew(force)
return .ForceNew(force)
case let ("forcePolling", force as Bool):
return .forcePolling(force)
return .ForcePolling(force)
case let ("forceWebsockets", force as Bool):
return .forceWebsockets(force)
case let ("handleQueue", queue as DispatchQueue):
return .handleQueue(queue)
return .ForceWebsockets(force)
case let ("handleQueue", queue as dispatch_queue_t):
return .HandleQueue(queue)
case let ("log", log as Bool):
return .log(log)
return .Log(log)
case let ("logger", logger as SocketLogger):
return .logger(logger)
return .Logger(logger)
case let ("nsp", nsp as String):
return .nsp(nsp)
return .Nsp(nsp)
case let ("path", path as String):
return .path(path)
return .Path(path)
case let ("reconnects", reconnects as Bool):
return .reconnects(reconnects)
return .Reconnects(reconnects)
case let ("reconnectAttempts", attempts as Int):
return .reconnectAttempts(attempts)
return .ReconnectAttempts(attempts)
case let ("reconnectWait", wait as Int):
return .reconnectWait(wait)
return .ReconnectWait(wait)
case let ("secure", secure as Bool):
return .secure(secure)
return .Secure(secure)
case let ("security", security as SSLSecurity):
return .security(security)
return .Security(security)
case let ("selfSigned", selfSigned as Bool):
return .selfSigned(selfSigned)
case let ("sessionDelegate", delegate as URLSessionDelegate):
return .sessionDelegate(delegate)
return .SelfSigned(selfSigned)
case let ("sessionDelegate", delegate as NSURLSessionDelegate):
return .SessionDelegate(delegate)
case let ("voipEnabled", enable as Bool):
return .voipEnabled(enable)
return .VoipEnabled(enable)
default:
return nil
}
@@ -93,7 +93,7 @@ extension NSDictionary {
var options = [] as SocketIOClientConfiguration
for (rawKey, value) in self {
if let key = rawKey as? String, let opt = NSDictionary.keyValueToSocketIOClientOption(key: key, value: value) {
if let key = rawKey as? String, opt = NSDictionary.keyValueToSocketIOClientOption(key, value: value) {
options.insert(opt)
}
}
@@ -103,9 +103,9 @@ extension NSDictionary {
}
extension String {
func toArray() throws -> [Any] {
guard let stringData = data(using: .utf8, allowLossyConversion: false) else { return [] }
guard let array = try JSONSerialization.jsonObject(with: stringData, options: .mutableContainers) as? [Any] else {
func toArray() throws -> [AnyObject] {
guard let stringData = dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) else { return [] }
guard let array = try NSJSONSerialization.JSONObjectWithData(stringData, options: .MutableContainers) as? [AnyObject] else {
throw JSONError.notArray
}
@@ -113,8 +113,8 @@ extension String {
}
func toNSDictionary() throws -> NSDictionary {
guard let binData = data(using: .utf8, allowLossyConversion: false) else { return [:] }
guard let json = try JSONSerialization.jsonObject(with: binData, options: .allowFragments) as? NSDictionary else {
guard let binData = dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) else { return [:] }
guard let json = try NSJSONSerialization.JSONObjectWithData(binData, options: .AllowFragments) as? NSDictionary else {
throw JSONError.notNSDictionary
}
@@ -122,6 +122,6 @@ extension String {
}
func urlEncode() -> String? {
return addingPercentEncoding(withAllowedCharacters: .allowedURLCharacterSet)
return stringByAddingPercentEncodingWithAllowedCharacters(.allowedURLCharacterSet)
}
}
+114 -111
View File
@@ -25,13 +25,13 @@
import Foundation
public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable {
public let socketURL: URL
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:
case .Connected:
reconnecting = false
currentReconnectAttempt = 0
default:
@@ -46,10 +46,10 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
public var reconnects = true
public var reconnectWait = 10
private let ackQueue = DispatchQueue(label: "com.socketio.ackQueue", attributes: [])
private let emitQueue = DispatchQueue(label: "com.socketio.emitQueue", attributes: [])
private let ackQueue = dispatch_queue_create("com.socketio.ackQueue", DISPATCH_QUEUE_SERIAL)
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
private let logType = "SocketIOClient"
private let parseQueue = DispatchQueue(label: "com.socketio.parseQueue", attributes: [])
private let parseQueue = dispatch_queue_create("com.socketio.parseQueue", DISPATCH_QUEUE_SERIAL)
private var anyHandler: ((SocketAnyEvent) -> Void)?
private var currentReconnectAttempt = 0
@@ -58,7 +58,7 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
private var reconnecting = false
private(set) var currentAck = -1
private(set) var handleQueue = DispatchQueue.main
private(set) var handleQueue = dispatch_get_main_queue()
private(set) var reconnectAttempts = -1
var waitingPackets = [SocketPacket]()
@@ -67,39 +67,39 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
return nsp + "#" + (engine?.sid ?? "")
}
/// Type safe way to create a new SocketIOClient. opts can be omitted
public init(socketURL: URL, config: SocketIOClientConfiguration = []) {
/// Type safe way to create a new SocketIOClient. config can be omitted
public init(socketURL: NSURL, config: SocketIOClientConfiguration = []) {
self.config = config
self.socketURL = socketURL
if socketURL.absoluteString.hasPrefix("https://") {
self.config.insert(.secure(true))
if socketURL.absoluteString?.hasPrefix("https://") ?? false {
self.config.insert(.Secure(true))
}
for option in config {
switch option {
case let .reconnects(reconnects):
case let .Reconnects(reconnects):
self.reconnects = reconnects
case let .reconnectAttempts(attempts):
case let .ReconnectAttempts(attempts):
reconnectAttempts = attempts
case let .reconnectWait(wait):
case let .ReconnectWait(wait):
reconnectWait = abs(wait)
case let .nsp(nsp):
case let .Nsp(nsp):
self.nsp = nsp
case let .log(log):
case let .Log(log):
DefaultSocketLogger.Logger.log = log
case let .logger(logger):
case let .Logger(logger):
DefaultSocketLogger.Logger = logger
case let .handleQueue(queue):
case let .HandleQueue(queue):
handleQueue = queue
case let .forceNew(force):
case let .ForceNew(force):
forceNew = force
default:
continue
}
}
self.config.insert(.path("/socket.io/"), replacing: false)
self.config.insert(.Path("/socket.io/"), replacing: false)
super.init()
}
@@ -107,16 +107,16 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
/// 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, config: NSDictionary?) {
self.init(socketURL: socketURL as URL, config: config?.toSocketConfiguration() ?? [])
self.init(socketURL: socketURL, config: config?.toSocketConfiguration() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Client is being released", type: logType)
engine?.disconnect(reason: "Client Deinit")
engine?.disconnect("Client Deinit")
}
private func addEngine() -> SocketEngineSpec {
DefaultSocketLogger.Logger.log("Adding engine", type: logType, args: "")
DefaultSocketLogger.Logger.log("Adding engine", type: logType)
engine = SocketEngine(client: self, url: socketURL, config: config)
@@ -125,20 +125,19 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
/// Connect to the server.
public func connect() {
connect(timeoutAfter: 0, withHandler: nil)
connect(timeoutAfter: 0, withTimeoutHandler: nil)
}
/// Connect to the server. If we aren't connected after timeoutAfter, call withHandler
/// 0 Never times out
public func connect(timeoutAfter: Int, withHandler handler: (() -> Void)?) {
/// 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)")
guard status != .connected else {
guard status != .Connected else {
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket", type: logType)
return
}
status = .connecting
status = .Connecting
if engine == nil || forceNew {
addEngine().connect()
@@ -148,25 +147,25 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
guard timeoutAfter != 0 else { return }
let time = DispatchTime.now() + Double(Int64(timeoutAfter) * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
handleQueue.asyncAfter(deadline: time) {[weak self] in
guard let this = self, this.status != .connected && this.status != .disconnected else { return }
dispatch_after(time, handleQueue) {[weak self] in
guard let this = self where this.status != .Connected && this.status != .Disconnected else { return }
this.status = .disconnected
this.engine?.disconnect(reason: "Connect timeout")
this.status = .Disconnected
this.engine?.disconnect("Connect timeout")
handler?()
}
}
private func createOnAck(_ items: [Any]) -> OnAckCallback {
private func createOnAck(items: [AnyObject]) -> OnAckCallback {
currentAck += 1
return {[weak self, ack = currentAck] timeout, callback in
guard let this = self else { return }
this.ackQueue.sync() {
dispatch_sync(this.ackQueue) {
this.ackHandlers.addAck(ack, callback: callback)
}
@@ -174,9 +173,9 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
this._emit(items, ack: ack)
if timeout != 0 {
let time = DispatchTime.now() + Double(Int64(timeout * NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
this.handleQueue.asyncAfter(deadline: time) {
dispatch_after(time, this.ackQueue) {
this.ackHandlers.timeoutAck(ack, onQueue: this.handleQueue)
}
}
@@ -185,7 +184,7 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
func didConnect() {
DefaultSocketLogger.Logger.log("Socket connected", type: logType)
status = .connected
status = .Connected
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
@@ -193,15 +192,15 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
}
func didDisconnect(reason: String) {
guard status != .disconnected else { return }
guard status != .Disconnected else { return }
DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason)
reconnecting = false
status = .disconnected
status = .Disconnected
// Make sure the engine is actually dead.
engine?.disconnect(reason: reason)
engine?.disconnect(reason)
handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
@@ -209,17 +208,17 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
public func disconnect() {
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
didDisconnect(reason: "Disconnect")
didDisconnect("Disconnect")
}
/// Send a message to the server
public func emit(_ event: String, _ items: SocketData...) {
emit(event, with: items)
public func emit(event: String, _ items: AnyObject...) {
emit(event, withItems: items)
}
/// Same as emit, but meant for Objective-C
public func emit(_ event: String, with items: [Any]) {
guard status == .connected else {
public func emit(event: String, withItems items: [AnyObject]) {
guard status == .Connected else {
handleEvent("error", data: ["Tried emitting \(event) when not connected"], isInternalMessage: true)
return
}
@@ -229,18 +228,18 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
/// 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: SocketData...) -> OnAckCallback {
return emitWithAck(event, with: items)
public func emitWithAck(event: String, _ items: AnyObject...) -> OnAckCallback {
return emitWithAck(event, withItems: items)
}
/// Same as emitWithAck, but for Objective-C
public func emitWithAck(_ event: String, with items: [Any]) -> OnAckCallback {
public func emitWithAck(event: String, withItems items: [AnyObject]) -> OnAckCallback {
return createOnAck([event] + items)
}
private func _emit(_ data: [Any], ack: Int? = nil) {
emitQueue.async {
guard self.status == .connected else {
private func _emit(data: [AnyObject], ack: Int? = nil) {
dispatch_async(emitQueue) {
guard self.status == .Connected else {
self.handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
return
}
@@ -255,31 +254,31 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
}
// If the server wants to know that the client received data
func emitAck(_ ack: Int, with items: [Any]) {
emitQueue.async {
guard self.status == .connected else { return }
let packet = SocketPacket.packetFromEmit(items, id: ack, nsp: self.nsp, ack: true)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting Ack: %@", type: self.logType, args: str)
self.engine?.send(str, withData: packet.binary)
func emitAck(ack: Int, withItems items: [AnyObject]) {
dispatch_async(emitQueue) {
if self.status == .Connected {
let packet = SocketPacket.packetFromEmit(items, id: ack ?? -1, nsp: self.nsp, ack: true)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting Ack: %@", type: self.logType, args: str)
self.engine?.send(str, withData: packet.binary)
}
}
}
public func engineDidClose(reason: String) {
waitingPackets.removeAll()
if status != .disconnected {
status = .notConnected
if status != .Disconnected {
status = .NotConnected
}
if status == .disconnected || !reconnects {
didDisconnect(reason: reason)
if status == .Disconnected || !reconnects {
didDisconnect(reason)
} else if !reconnecting {
reconnecting = true
tryReconnect(reason: reason)
tryReconnectWithReason(reason)
}
}
@@ -295,27 +294,27 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
}
// Called when the socket gets an ack for something it sent
func handleAck(_ ack: Int, data: [Any]) {
guard status == .connected else { return }
func handleAck(ack: Int, data: [AnyObject]) {
guard status == .Connected else { return }
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data)
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
handleQueue.async() {
self.ackHandlers.executeAck(ack, with: data, onQueue: self.handleQueue)
dispatch_async(ackQueue) {
self.ackHandlers.executeAck(ack, items: data, onQueue: self.handleQueue)
}
}
/// Causes an event to be handled. Only use if you know what you're doing.
public func handleEvent(_ event: String, data: [Any], isInternalMessage: Bool, withAck ack: Int = -1) {
guard status == .connected || isInternalMessage else { return }
public func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool, withAck ack: Int = -1) {
guard status == .Connected || isInternalMessage else { return }
DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data)
DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data ?? "")
handleQueue.async {
dispatch_async(handleQueue) {
self.anyHandler?(SocketAnyEvent(event: event, items: data))
for handler in self.handlers where handler.event == event {
handler.executeCallback(with: data, withAck: ack, withSocket: self)
handler.executeCallback(data, withAck: ack, withSocket: self)
}
}
}
@@ -329,7 +328,7 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
}
/// Joins namespace
public func joinNamespace(_ namespace: String) {
public func joinNamespace(namespace: String) {
nsp = namespace
if nsp != "/" {
@@ -339,14 +338,14 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
}
/// Removes handler(s) based on name
public func off(_ event: String) {
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`
public func off(id: UUID) {
public func off(id id: NSUUID) {
DefaultSocketLogger.Logger.log("Removing handler with id: %@", type: logType, args: id)
handlers = handlers.filter({ $0.id != id })
@@ -354,11 +353,10 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
/// Adds a handler for an event.
/// Returns: A unique id for the handler
@discardableResult
public func on(_ event: String, callback: @escaping NormalCallback) -> UUID {
public func on(event: String, callback: NormalCallback) -> NSUUID {
DefaultSocketLogger.Logger.log("Adding handler for event: %@", type: logType, args: event)
let handler = SocketEventHandler(event: event, id: UUID(), callback: callback)
let handler = SocketEventHandler(event: event, id: NSUUID(), callback: callback)
handlers.append(handler)
return handler.id
@@ -366,11 +364,10 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
/// Adds a single-use handler for an event.
/// Returns: A unique id for the handler
@discardableResult
public func once(_ event: String, callback: @escaping NormalCallback) -> UUID {
public func once(event: String, callback: NormalCallback) -> NSUUID {
DefaultSocketLogger.Logger.log("Adding once handler for event: %@", type: logType, args: event)
let id = UUID()
let id = NSUUID()
let handler = SocketEventHandler(event: event, id: id) {[weak self] data, ack in
guard let this = self else { return }
@@ -384,34 +381,38 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
}
/// Adds a handler that will be called on every event.
public func onAny(_ handler: @escaping (SocketAnyEvent) -> Void) {
public func onAny(handler: (SocketAnyEvent) -> Void) {
anyHandler = handler
}
public func parseEngineMessage(_ msg: String) {
public func parseEngineMessage(msg: String) {
DefaultSocketLogger.Logger.log("Should parse message: %@", type: "SocketIOClient", args: msg)
parseQueue.async { self.parseSocketMessage(msg) }
dispatch_async(parseQueue) {
self.parseSocketMessage(msg)
}
}
public func parseEngineBinaryData(_ data: Data) {
parseQueue.async { self.parseBinaryData(data) }
public func parseEngineBinaryData(data: NSData) {
dispatch_async(parseQueue) {
self.parseBinaryData(data)
}
}
/// Tries to reconnect to the server.
public func reconnect() {
guard !reconnecting else { return }
engine?.disconnect(reason: "manual reconnect")
engine?.disconnect("manual reconnect")
}
/// Removes all handlers.
/// Can be used after disconnecting to break any potential remaining retain cycles.
public func removeAllHandlers() {
handlers.removeAll(keepingCapacity: false)
handlers.removeAll(keepCapacity: false)
}
private func tryReconnect(reason: String) {
private func tryReconnectWithReason(reason: String) {
guard reconnecting else { return }
DefaultSocketLogger.Logger.log("Starting reconnect", type: logType)
@@ -424,35 +425,37 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
guard reconnecting else { return }
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
return didDisconnect(reason: "Reconnect Failed")
return didDisconnect("Reconnect Failed")
}
DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType)
handleEvent("reconnectAttempt", data: [(reconnectAttempts - currentReconnectAttempt)], isInternalMessage: true)
handleEvent("reconnectAttempt", data: [reconnectAttempts - currentReconnectAttempt],
isInternalMessage: true)
currentReconnectAttempt += 1
connect()
let deadline = DispatchTime.now() + Double(Int64(UInt64(reconnectWait) * NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(reconnectWait) * NSEC_PER_SEC))
DispatchQueue.main.asyncAfter(deadline: deadline, execute: _tryReconnect)
dispatch_after(time, dispatch_get_main_queue(), _tryReconnect)
}
// Test properties
}
// Test extensions
extension SocketIOClient {
var testHandlers: [SocketEventHandler] {
return handlers
}
func setTestable() {
status = .connected
status = .Connected
}
func setTestEngine(_ engine: SocketEngineSpec?) {
func setTestEngine(engine: SocketEngineSpec?) {
self.engine = engine
}
func emitTest(event: String, _ data: Any...) {
func emitTest(event: String, _ data: AnyObject...) {
_emit([event] + data)
}
}
+12 -13
View File
@@ -22,7 +22,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public struct SocketIOClientConfiguration : ExpressibleByArrayLiteral, Collection, MutableCollection {
public struct SocketIOClientConfiguration : ArrayLiteralConvertible, CollectionType, MutableCollectionType {
public typealias Element = SocketIOClientOption
public typealias Index = Array<SocketIOClientOption>.Index
public typealias Generator = Array<SocketIOClientOption>.Generator
@@ -42,7 +42,7 @@ public struct SocketIOClientConfiguration : ExpressibleByArrayLiteral, Collectio
return backingArray.isEmpty
}
public var count: Index.Stride {
public var count: Index.Distance {
return backingArray.count
}
@@ -75,11 +75,7 @@ public struct SocketIOClientConfiguration : ExpressibleByArrayLiteral, Collectio
}
public func generate() -> Generator {
return backingArray.makeIterator()
}
public func index(after i: Index) -> Index {
return backingArray.index(after: i)
return backingArray.generate()
}
public mutating func insert(_ element: Element, replacing replace: Bool = true) {
@@ -94,15 +90,18 @@ public struct SocketIOClientConfiguration : ExpressibleByArrayLiteral, Collectio
backingArray.append(element)
}
public func prefix(upTo end: Index) -> SubSequence {
return backingArray.prefix(upTo: end)
@warn_unused_result
public func prefixUpTo(end: Index) -> SubSequence {
return backingArray.prefixUpTo(end)
}
public func prefix(through position: Index) -> SubSequence {
return backingArray.prefix(through: position)
@warn_unused_result
public func prefixThrough(position: Index) -> SubSequence {
return backingArray.prefixThrough(position)
}
public func suffix(from start: Index) -> SubSequence {
return backingArray.suffix(from: start)
@warn_unused_result
public func suffixFrom(start: Index) -> SubSequence {
return backingArray.suffixFrom(start)
}
}
+64 -64
View File
@@ -25,123 +25,123 @@
import Foundation
protocol ClientOption : CustomStringConvertible, Equatable {
func getSocketIOOptionValue() -> Any
func getSocketIOOptionValue() -> AnyObject
}
public enum SocketIOClientOption : ClientOption {
case connectParams([String: Any])
case cookies([HTTPCookie])
case doubleEncodeUTF8(Bool)
case extraHeaders([String: String])
case forceNew(Bool)
case forcePolling(Bool)
case forceWebsockets(Bool)
case handleQueue(DispatchQueue)
case log(Bool)
case logger(SocketLogger)
case nsp(String)
case path(String)
case reconnects(Bool)
case reconnectAttempts(Int)
case reconnectWait(Int)
case secure(Bool)
case security(SSLSecurity)
case selfSigned(Bool)
case sessionDelegate(URLSessionDelegate)
case voipEnabled(Bool)
case ConnectParams([String: AnyObject])
case Cookies([NSHTTPCookie])
case DoubleEncodeUTF8(Bool)
case ExtraHeaders([String: String])
case ForceNew(Bool)
case ForcePolling(Bool)
case ForceWebsockets(Bool)
case HandleQueue(dispatch_queue_t)
case Log(Bool)
case Logger(SocketLogger)
case Nsp(String)
case Path(String)
case Reconnects(Bool)
case ReconnectAttempts(Int)
case ReconnectWait(Int)
case Secure(Bool)
case Security(SSLSecurity)
case SelfSigned(Bool)
case SessionDelegate(NSURLSessionDelegate)
case VoipEnabled(Bool)
public var description: String {
let description: String
switch self {
case .connectParams:
case .ConnectParams:
description = "connectParams"
case .cookies:
case .Cookies:
description = "cookies"
case .doubleEncodeUTF8:
case .DoubleEncodeUTF8:
description = "doubleEncodeUTF8"
case .extraHeaders:
case .ExtraHeaders:
description = "extraHeaders"
case .forceNew:
case .ForceNew:
description = "forceNew"
case .forcePolling:
case .ForcePolling:
description = "forcePolling"
case .forceWebsockets:
case .ForceWebsockets:
description = "forceWebsockets"
case .handleQueue:
case .HandleQueue:
description = "handleQueue"
case .log:
case .Log:
description = "log"
case .logger:
case .Logger:
description = "logger"
case .nsp:
case .Nsp:
description = "nsp"
case .path:
case .Path:
description = "path"
case .reconnects:
case .Reconnects:
description = "reconnects"
case .reconnectAttempts:
case .ReconnectAttempts:
description = "reconnectAttempts"
case .reconnectWait:
case .ReconnectWait:
description = "reconnectWait"
case .secure:
case .Secure:
description = "secure"
case .selfSigned:
description = "selfSigned"
case .security:
case .Security:
description = "security"
case .sessionDelegate:
case .SelfSigned:
description = "selfSigned"
case .SessionDelegate:
description = "sessionDelegate"
case .voipEnabled:
case .VoipEnabled:
description = "voipEnabled"
}
return description
}
func getSocketIOOptionValue() -> Any {
let value: Any
func getSocketIOOptionValue() -> AnyObject {
let value: AnyObject
switch self {
case let .connectParams(params):
case let .ConnectParams(params):
value = params
case let .cookies(cookies):
case let .Cookies(cookies):
value = cookies
case let .doubleEncodeUTF8(encode):
case let .DoubleEncodeUTF8(encode):
value = encode
case let .extraHeaders(headers):
case let .ExtraHeaders(headers):
value = headers
case let .forceNew(force):
case let .ForceNew(force):
value = force
case let .forcePolling(force):
case let .ForcePolling(force):
value = force
case let .forceWebsockets(force):
case let .ForceWebsockets(force):
value = force
case let .handleQueue(queue):
case let .HandleQueue(queue):
value = queue
case let .log(log):
case let .Log(log):
value = log
case let .logger(logger):
case let .Logger(logger):
value = logger
case let .nsp(nsp):
case let .Nsp(nsp):
value = nsp
case let .path(path):
case let .Path(path):
value = path
case let .reconnects(reconnects):
case let .Reconnects(reconnects):
value = reconnects
case let .reconnectAttempts(attempts):
case let .ReconnectAttempts(attempts):
value = attempts
case let .reconnectWait(wait):
case let .ReconnectWait(wait):
value = wait
case let .secure(secure):
case let .Secure(secure):
value = secure
case let .security(security):
case let .Security(security):
value = security
case let .selfSigned(signed):
case let .SelfSigned(signed):
value = signed
case let .sessionDelegate(delegate):
case let .SessionDelegate(delegate):
value = delegate
case let .voipEnabled(enabled):
case let .VoipEnabled(enabled):
value = enabled
}
+3 -3
View File
@@ -29,9 +29,9 @@ protocol SocketIOClientSpec : class {
func didConnect()
func didDisconnect(reason: String)
func didError(reason: String)
func handleAck(_ ack: Int, data: [Any])
func handleEvent(_ event: String, data: [Any], isInternalMessage: Bool, withAck ack: Int)
func joinNamespace(_ namespace: String)
func handleAck(ack: Int, data: [AnyObject])
func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool, withAck ack: Int)
func joinNamespace(namespace: String)
}
extension SocketIOClientSpec {
+1 -1
View File
@@ -28,5 +28,5 @@ import Foundation
///
/// **Disconnected**: connected before
@objc public enum SocketIOClientStatus : Int {
case notConnected, disconnected, connecting, connected
case NotConnected, Disconnected, Connecting, Connected
}
+8 -8
View File
@@ -29,28 +29,28 @@ public protocol SocketLogger : class {
var log: Bool { get set }
/// Normal log messages
func log(_ message: String, type: String, args: Any...)
func log(message: String, type: String, args: AnyObject...)
/// Error Messages
func error(_ message: String, type: String, args: Any...)
func error(message: String, type: String, args: AnyObject...)
}
public extension SocketLogger {
func log(_ message: String, type: String, args: Any...) {
func log(message: String, type: String, args: AnyObject...) {
abstractLog("LOG", message: message, type: type, args: args)
}
func error(_ message: String, type: String, args: Any...) {
func error(message: String, type: String, args: AnyObject...) {
abstractLog("ERROR", message: message, type: type, args: args)
}
private func abstractLog(_ logType: String, message: String, type: String, args: [Any]) {
private func abstractLog(logType: String, message: String, type: String, args: [AnyObject]) {
guard log else { return }
let newArgs = args.map({arg -> CVarArg in String(describing: arg)})
let messageFormat = String(format: message, arguments: newArgs)
let newArgs = args.map({arg -> CVarArgType in String(arg)})
let replaced = String(format: message, arguments: newArgs)
NSLog("\(logType) \(type): %@", messageFormat)
NSLog("%@ %@: %@", logType, type, replaced)
}
}
+37 -43
View File
@@ -27,7 +27,7 @@ import Foundation
struct SocketPacket {
enum PacketType: Int {
case connect, disconnect, event, ack, error, binaryEvent, binaryAck
case Connect, Disconnect, Event, Ack, Error, BinaryEvent, BinaryAck
}
private let placeholders: Int
@@ -38,10 +38,11 @@ struct SocketPacket {
let id: Int
let type: PacketType
var binary: [Data]
var data: [Any]
var args: [Any] {
if type == .event || type == .binaryEvent && data.count != 0 {
var binary: [NSData]
var data: [AnyObject]
var args: [AnyObject] {
if type == .Event || type == .BinaryEvent && data.count != 0 {
return Array(data.dropFirst())
} else {
return data
@@ -50,19 +51,19 @@ struct SocketPacket {
var description: String {
return "SocketPacket {type: \(String(type.rawValue)); data: " +
"\(String(describing: data)); id: \(id); placeholders: \(placeholders); nsp: \(nsp)}"
"\(String(data)); id: \(id); placeholders: \(placeholders); nsp: \(nsp)}"
}
var event: String {
return String(describing: data[0])
return String(data[0])
}
var packetString: String {
return createPacketString()
}
init(type: PacketType, data: [Any] = [Any](), id: Int = -1, nsp: String, placeholders: Int = 0,
binary: [Data] = [Data]()) {
init(type: PacketType, data: [AnyObject] = [AnyObject](), id: Int = -1,
nsp: String, placeholders: Int = 0, binary: [NSData] = [NSData]()) {
self.data = data
self.id = id
self.nsp = nsp
@@ -71,7 +72,7 @@ struct SocketPacket {
self.binary = binary
}
mutating func addData(_ data: Data) -> Bool {
mutating func addData(data: NSData) -> Bool {
if placeholders == binary.count {
return true
}
@@ -86,7 +87,7 @@ struct SocketPacket {
}
}
private func completeMessage(_ message: String) -> String {
private func completeMessage(message: String) -> String {
let restOfMessage: String
if data.count == 0 {
@@ -95,7 +96,7 @@ struct SocketPacket {
do {
let jsonSend = try data.toJSON()
guard let jsonString = String(data: jsonSend, encoding: .utf8) else { return message + "[]" }
guard let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding) else { return message + "[]" }
restOfMessage = jsonString
} catch {
@@ -111,9 +112,9 @@ struct SocketPacket {
private func createPacketString() -> String {
let typeString = String(type.rawValue)
// Binary count?
let binaryCountString = typeString + (type == .binaryEvent || type == .binaryAck ? "\(String(binary.count))-" : "")
let binaryCountString = typeString + (type == .BinaryEvent || type == .BinaryAck ? String(binary.count) + "-" : "")
// Namespace?
let nspString = binaryCountString + (nsp != "/" ? "\(nsp)," : "")
let nspString = binaryCountString + (nsp != "/" ? nsp + "," : "")
// Ack number?
let idString = nspString + (id != -1 ? String(id) : "")
@@ -131,21 +132,18 @@ struct SocketPacket {
// If object is a collection it will recurse
// Returns the object if it is not a placeholder or the corresponding
// binary data
private func _fillInPlaceholders(_ object: Any) -> Any {
private func _fillInPlaceholders(object: AnyObject) -> AnyObject {
switch object {
case let dict as [String: Any]:
case let dict as NSDictionary:
if dict["_placeholder"] as? Bool ?? false {
return binary[dict["num"] as! Int]
} else {
return dict.reduce([String: Any](), {cur, keyValue in
var cur = cur
cur[keyValue.0] = _fillInPlaceholders(keyValue.1)
return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in
cur[keyValue.0 as! NSCopying] = _fillInPlaceholders(keyValue.1)
return cur
})
}
case let arr as [Any]:
case let arr as [AnyObject]:
return arr.map(_fillInPlaceholders)
default:
return object
@@ -154,22 +152,22 @@ struct SocketPacket {
}
extension SocketPacket {
private static func findType(_ binCount: Int, ack: Bool) -> PacketType {
private static func findType(binCount: Int, ack: Bool) -> PacketType {
switch binCount {
case 0 where !ack:
return .event
return .Event
case 0 where ack:
return .ack
return .Ack
case _ where !ack:
return .binaryEvent
return .BinaryEvent
case _ where ack:
return .binaryAck
return .BinaryAck
default:
return .error
return .Error
}
}
static func packetFromEmit(_ items: [Any], id: Int, nsp: String, ack: Bool) -> SocketPacket {
static func packetFromEmit(items: [AnyObject], id: Int, nsp: String, ack: Bool) -> SocketPacket {
let (parsedData, binary) = deconstructData(items)
let packet = SocketPacket(type: findType(binary.count, ack: ack), data: parsedData,
id: id, nsp: nsp, binary: binary)
@@ -180,23 +178,19 @@ extension SocketPacket {
private extension SocketPacket {
// Recursive function that looks for NSData in collections
static func shred(_ data: Any, binary: inout [Data]) -> Any {
let placeholder = ["_placeholder": true, "num": binary.count] as [String : Any]
static func shred(data: AnyObject, inout binary: [NSData]) -> AnyObject {
let placeholder = ["_placeholder": true, "num": binary.count]
switch data {
case let bin as Data:
case let bin as NSData:
binary.append(bin)
return placeholder
case let arr as [Any]:
case let arr as [AnyObject]:
return arr.map({shred($0, binary: &binary)})
case let dict as [String: Any]:
return dict.reduce([String: Any](), {cur, keyValue in
var mutCur = cur
mutCur[keyValue.0] = shred(keyValue.1, binary: &binary)
return mutCur
case let dict as NSDictionary:
return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in
cur[keyValue.0 as! NSCopying] = shred(keyValue.1, binary: &binary)
return cur
})
default:
return data
@@ -205,8 +199,8 @@ private extension SocketPacket {
// Removes binary data from emit data
// Returns a type containing the de-binaryed data and the binary
static func deconstructData(_ data: [Any]) -> ([Any], [Data]) {
var binary = [Data]()
static func deconstructData(data: [AnyObject]) -> ([AnyObject], [NSData]) {
var binary = [NSData]()
return (data.map({shred($0, binary: &binary)}), binary)
}
+48 -47
View File
@@ -23,16 +23,16 @@
import Foundation
protocol SocketParsable : SocketIOClientSpec {
func parseBinaryData(_ data: Data)
func parseSocketMessage(_ message: String)
func parseBinaryData(data: NSData)
func parseSocketMessage(message: String)
}
extension SocketParsable {
private func isCorrectNamespace(_ nsp: String) -> Bool {
private func isCorrectNamespace(nsp: String) -> Bool {
return nsp == self.nsp
}
private func handleConnect(_ packetNamespace: String) {
private func handleConnect(packetNamespace: String) {
if packetNamespace == "/" && nsp != "/" {
joinNamespace(nsp)
} else {
@@ -40,21 +40,21 @@ extension SocketParsable {
}
}
private func handlePacket(_ pack: SocketPacket) {
private func handlePacket(pack: SocketPacket) {
switch pack.type {
case .event where isCorrectNamespace(pack.nsp):
case .Event where isCorrectNamespace(pack.nsp):
handleEvent(pack.event, data: pack.args, isInternalMessage: false, withAck: pack.id)
case .ack where isCorrectNamespace(pack.nsp):
case .Ack where isCorrectNamespace(pack.nsp):
handleAck(pack.id, data: pack.data)
case .binaryEvent where isCorrectNamespace(pack.nsp):
case .BinaryEvent where isCorrectNamespace(pack.nsp):
waitingPackets.append(pack)
case .binaryAck where isCorrectNamespace(pack.nsp):
case .BinaryAck where isCorrectNamespace(pack.nsp):
waitingPackets.append(pack)
case .connect:
case .Connect:
handleConnect(pack.nsp)
case .disconnect:
didDisconnect(reason: "Got Disconnect")
case .error:
case .Disconnect:
didDisconnect("Got Disconnect")
case .Error:
handleEvent("error", data: pack.data, isInternalMessage: true, withAck: pack.id)
default:
DefaultSocketLogger.Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description)
@@ -62,93 +62,93 @@ extension SocketParsable {
}
/// Parses a messsage from the engine. Returning either a string error or a complete SocketPacket
func parseString(_ message: String) -> Either<String, SocketPacket> {
func parseString(message: String) -> Either<String, SocketPacket> {
var reader = SocketStringReader(message: message)
guard let type = Int(reader.read(count: 1)).flatMap({ SocketPacket.PacketType(rawValue: $0) }) else {
return .left("Invalid packet type")
guard let type = SocketPacket.PacketType(rawValue: Int(reader.read(1)) ?? -1) else {
return .Left("Invalid packet type")
}
if !reader.hasNext {
return .right(SocketPacket(type: type, nsp: "/"))
return .Right(SocketPacket(type: type, nsp: "/"))
}
var namespace = "/"
var placeholders = -1
if type == .binaryEvent || type == .binaryAck {
if let holders = Int(reader.readUntilOccurence(of: "-")) {
if type == .BinaryEvent || type == .BinaryAck {
if let holders = Int(reader.readUntilStringOccurence("-")) {
placeholders = holders
} else {
return .left("Invalid packet")
return .Left("Invalid packet")
}
}
if reader.currentCharacter == "/" {
namespace = reader.readUntilOccurence(of: ",")
namespace = reader.readUntilStringOccurence(",") ?? reader.readUntilEnd()
}
if !reader.hasNext {
return .right(SocketPacket(type: type, nsp: namespace, placeholders: placeholders))
return .Right(SocketPacket(type: type, nsp: namespace, placeholders: placeholders))
}
var idString = ""
if type == .error {
reader.advance(by: -1)
if type == .Error {
reader.advanceIndexBy(-1)
} else {
while reader.hasNext {
if let int = Int(reader.read(count: 1)) {
if let int = Int(reader.read(1)) {
idString += String(int)
} else {
reader.advance(by: -2)
reader.advanceIndexBy(-2)
break
}
}
}
let d = message[reader.currentIndex.advancedBy(1)..<message.endIndex]
var dataArray = message[message.characters.index(reader.currentIndex, offsetBy: 1)..<message.endIndex]
if type == .error && !dataArray.hasPrefix("[") && !dataArray.hasSuffix("]") {
dataArray = "[" + dataArray + "]"
}
switch parseData(dataArray) {
case let .left(err):
return .left(err)
case let .right(data):
return .right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
switch parseData(d) {
case let .Left(err):
// Errors aren't always enclosed in an array
if case let .Right(data) = parseData("\([d as AnyObject])") {
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
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))
}
}
// Parses data for events
private func parseData(_ data: String) -> Either<String, [Any]> {
private func parseData(data: String) -> Either<String, [AnyObject]> {
do {
return .right(try data.toArray())
return .Right(try data.toArray())
} catch {
return .left("Error parsing data for packet")
return .Left("Error parsing data for packet")
}
}
// Parses messages recieved
func parseSocketMessage(_ message: String) {
func parseSocketMessage(message: String) {
guard !message.isEmpty else { return }
DefaultSocketLogger.Logger.log("Parsing %@", type: "SocketParser", args: message)
switch parseString(message) {
case let .left(err):
case let .Left(err):
DefaultSocketLogger.Logger.error("\(err): %@", type: "SocketParser", args: message)
case let .right(pack):
case let .Right(pack):
DefaultSocketLogger.Logger.log("Decoded packet as: %@", type: "SocketParser", args: pack.description)
handlePacket(pack)
}
}
func parseBinaryData(_ data: Data) {
func parseBinaryData(data: NSData) {
guard !waitingPackets.isEmpty else {
DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser")
return
@@ -159,8 +159,9 @@ extension SocketParsable {
let packet = waitingPackets.removeLast()
if packet.type != .binaryAck {
handleEvent(packet.event, data: packet.args, isInternalMessage: false, withAck: packet.id)
if packet.type != .BinaryAck {
handleEvent(packet.event, data: packet.args ?? [],
isInternalMessage: false, withAck: packet.id)
} else {
handleAck(packet.id, data: packet.args)
}
+10 -15
View File
@@ -38,36 +38,31 @@ struct SocketStringReader {
currentIndex = message.startIndex
}
@discardableResult
mutating func advance(by: Int) -> String.Index {
currentIndex = message.characters.index(currentIndex, offsetBy: by)
return currentIndex
mutating func advanceIndexBy(n: Int) {
currentIndex = currentIndex.advancedBy(n)
}
mutating func read(count: Int) -> String {
let readString = message[currentIndex..<message.characters.index(currentIndex, offsetBy: count)]
advance(by: count)
mutating func read(readLength: Int) -> String {
let readString = message[currentIndex..<currentIndex.advancedBy(readLength)]
advanceIndexBy(readLength)
return readString
}
mutating func readUntilOccurence(of string: String) -> String {
mutating func readUntilStringOccurence(string: String) -> String {
let substring = message[currentIndex..<message.endIndex]
guard let foundRange = substring.range(of: string) else {
guard let foundRange = substring.rangeOfString(string) else {
currentIndex = message.endIndex
return substring
}
advance(by: message.characters.distance(from: message.characters.startIndex, to: foundRange.lowerBound) + 1)
advanceIndexBy(message.startIndex.distanceTo(foundRange.startIndex) + 1)
return substring.substring(to: foundRange.lowerBound)
return substring.substringToIndex(foundRange.startIndex)
}
mutating func readUntilEnd() -> String {
return read(count: message.characters.distance(from: currentIndex, to: message.endIndex))
return read(currentIndex.distanceTo(message.endIndex))
}
}
+6 -21
View File
@@ -24,29 +24,14 @@
import Foundation
public protocol SocketData {}
public typealias AckCallback = ([AnyObject]) -> Void
public typealias NormalCallback = ([AnyObject], SocketAckEmitter) -> Void
public typealias OnAckCallback = (timeoutAfter: UInt64, callback: AckCallback) -> Void
extension Array : SocketData {}
extension Bool : SocketData {}
extension Dictionary : SocketData {}
extension Double : SocketData {}
extension Int : SocketData {}
extension NSArray : SocketData {}
extension Data : SocketData {}
extension NSData : SocketData {}
extension NSDictionary : SocketData {}
extension NSString : SocketData {}
extension NSNull : SocketData {}
extension String : SocketData {}
public typealias AckCallback = ([Any]) -> Void
public typealias NormalCallback = ([Any], SocketAckEmitter) -> Void
public typealias OnAckCallback = (_ timeoutAfter: UInt64, _ callback: @escaping AckCallback) -> Void
typealias Probe = (msg: String, type: SocketEnginePacketType, data: [Data])
typealias Probe = (msg: String, type: SocketEnginePacketType, data: [NSData])
typealias ProbeWaitQueue = [Probe]
enum Either<E, V> {
case left(E)
case right(V)
case Left(E)
case Right(V)
}
+254 -301
View File
File diff suppressed because it is too large. Load diff