Compare commits

...
40 Commits
Author SHA1 Message Date
Erik ff9c1bb67b bump version 2016-01-27 16:07:50 -05:00
Erik c92e146dfc small tweaks 2016-01-27 16:00:36 -05:00
Erik d71f81745e move websocketurl plus sid to computed property 2016-01-26 14:17:11 -05:00
Erik 228c0c7c9b small readme change 2016-01-26 11:28:32 -05:00
Erik Little d36ef10404 Merge pull request #289 from socketio/nsurl-based
Nsurl based
2016-01-26 11:24:19 -05:00
Erik c5c00510e5 remove unused property 2016-01-26 11:03:32 -05:00
Erik e38c4081ec comments and style 2016-01-26 10:51:53 -05:00
Erik 5060f90a79 we need to update the urls if connectparams changes 2016-01-25 19:13:17 -05:00
Erik 57670ec613 move connectparams to the engine 2016-01-25 19:02:47 -05:00
Erik 3f57c7e0a9 add default urls 2016-01-25 18:48:21 -05:00
Erik efe0d01592 update docs 2016-01-25 18:23:15 -05:00
Erik f9c665a542 for whatever reason I was able trigger a race condition because of the last commit 2016-01-25 17:23:57 -05:00
Erik b67b6abbdf engine polling to nsurl 2016-01-25 16:21:52 -05:00
Erik d912796fa5 engine websocket url to nsurl 2016-01-25 15:52:54 -05:00
Erik c9ac69f408 first pass at socketio/socket.io-client-swift#288 2016-01-25 14:55:58 -05:00
Erik cc7d96e3d5 remove trailing / from urls 2016-01-25 10:46:03 -05:00
Erik bf1104443a make engine send internal 2016-01-24 11:31:04 -05:00
Erik adf8692234 change log message 2016-01-22 18:16:30 -05:00
Erik 94f02e567a bump version 2016-01-21 10:07:52 -05:00
Erik 4eca685dc2 fix nuclearace/Socket.IO-Client-Swift#103 2016-01-21 10:04:55 -05:00
Erik 90f512e03b remove disconnect 2016-01-20 14:41:12 -05:00
Erik 7d8b0c89c5 bump version 2016-01-20 14:39:07 -05:00
Erik e45003210f revert to unbroken websocket version 2016-01-20 14:38:13 -05:00
Erik 4d07d2911f bump version 2016-01-18 15:55:18 -05:00
Erik 0d6e4af62f fix websocket bug 2016-01-18 15:54:28 -05:00
Erik 2e6803bd1a bump version 2016-01-18 12:44:37 -05:00
Erik bcb556b66c bump websocket 2016-01-18 10:03:16 -05:00
Erik d8b5293ca1 fix readme 2016-01-17 10:57:17 -05:00
Erik ec2aa703a3 Send close reason to engine 2016-01-17 10:30:34 -05:00
Erik c211ab140d We're always connecting anyway 2016-01-17 10:29:10 -05:00
Erik 5cab7dbb2f changes to swiftregex 2016-01-17 10:10:36 -05:00
Erik 0fc70e8be1 deprecate open() 2016-01-17 09:50:03 -05:00
Erik Little 609ce08351 Merge pull request #278 from socketio/standardize-module-name
Standardize module name
2016-01-17 09:29:33 -05:00
Erik e366e808ae update cocoapods documentation 2016-01-17 09:22:59 -05:00
Erik 03d5f56114 merge master 2016-01-17 08:48:34 -05:00
Erik 2cf448de72 change module name for cocoapods 2016-01-17 08:46:17 -05:00
Erik fb0c6a5612 Revert "is this what changes the cocoapods build name"
This reverts commit 3587c20718.
2016-01-17 08:45:20 -05:00
Erik a9633510ff update readme to reflect close being deprecated 2016-01-16 19:56:03 -05:00
Erik 3587c20718 is this what changes the cocoapods build name 2016-01-14 16:06:54 -05:00
Erik de3ca964ab work on standardizing module name 2016-01-14 16:01:46 -05:00
20 changed files with 300 additions and 288 deletions

No files matched your search

+12 -11
View File
@@ -5,7 +5,7 @@ Socket.IO-client for iOS/OS X.
##Example
```swift
let socket = SocketIOClient(socketURL: "localhost:8080", options: [.Log(true), .ForcePolling(true)])
let socket = SocketIOClient(socketURL: NSURL(string: "http://localhost:8080")!, options: [.Log(true), .ForcePolling(true)])
socket.on("connect") {data, ack in
print("socket connected")
@@ -26,7 +26,8 @@ socket.connect()
##Objective-C Example
```objective-c
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" options:@{@"log": @YES, @"forcePolling": @YES}];
NSURL* url = [[NSURL alloc] initWithString:@"http://localhost:8080"];
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:url options:@{@"log": @YES, @"forcePolling": @YES}];
[socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
NSLog(@"socket connected");
@@ -85,7 +86,7 @@ Carthage
-----------------
Add this line to your `Cartfile`:
```
github "socketio/socket.io-client-swift" ~> 5.1.0 # Or latest version
github "socketio/socket.io-client-swift" ~> 5.3.0 # Or latest version
```
Run `carthage update --platform ios,macosx`.
@@ -99,7 +100,7 @@ source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'Socket.IO-Client-Swift', '~> 5.1.0' # Or latest version
pod 'Socket.IO-Client-Swift', '~> 5.3.0' # Or latest version
```
Install pods:
@@ -112,13 +113,13 @@ Import the module:
Swift:
```swift
import Socket_IO_Client_Swift
import SocketIOClientSwift
```
Objective-C:
```Objective-C
#import <Socket_IO_Client_Swift/Socket_IO_Client_Swift-Swift.h>
#import <SocketIOClientSwift/SocketIOClientSwift-Swift.h>
```
CocoaSeeds
@@ -127,7 +128,7 @@ CocoaSeeds
Add this line to your `Seedfile`:
```
github "socketio/socket.io-client-swift", "v5.1.0", :files => "SocketIOClientSwift/*.swift" # Or latest version
github "socketio/socket.io-client-swift", "v5.3.0", :files => "Source/*.swift" # Or latest version
```
Run `seed install`.
@@ -136,9 +137,9 @@ Run `seed install`.
##API
Constructors
-----------
`init(var socketURL: String, options: Set<SocketIOClientOption> = [])` - Creates a new SocketIOClient. opts is a Set of SocketIOClientOption. If your socket.io server is secure, you need to specify `https` in your socketURL.
`init(var socketURL: NSURL, options: Set<SocketIOClientOption> = [])` - Creates a new SocketIOClient. options is a Set of SocketIOClientOption. If your socket.io server is secure, you need to specify `https` in your socketURL.
`convenience init(socketURL: String, options: NSDictionary?)` - Same as above, but meant for Objective-C. See Options on how convert between SocketIOClientOptions and dictionary keys.
`convenience init(socketURL: NSURL, options: NSDictionary?)` - Same as above, but meant for Objective-C. See Options on how convert between SocketIOClientOptions and dictionary keys.
Options
-------
@@ -157,7 +158,7 @@ case Cookies([NSHTTPCookie]) // An array of NSHTTPCookies. Passed during the han
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 SessionDelegate(NSURLSessionDelegate) // Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
case Path(String) // If the server uses a custom path. ex: `"/swift"`. Default is `""`
case Path(String) // If the server uses a custom path. ex: `"/swift/"`. Default is `""`
case ExtraHeaders([String: String]) // Adds custom headers to the initial request. Default is nil.
case HandleQueue(dispatch_queue_t) // The dispatch queue that handlers are run on. Default is the main queue.
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
@@ -176,7 +177,7 @@ Methods
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. `close()` - Closes the socket. Once a socket is closed it should not be reopened.
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.
13. `leaveNamespace()` - Causes the client to leave the nsp and go back to /
+4 -3
View File
@@ -1,11 +1,12 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.version = "5.1.0"
s.module_name = "SocketIOClientSwift"
s.version = "5.3.0"
s.summary = "Socket.IO-client for iOS and OS X"
s.description = <<-DESC
Socket.IO-client for iOS and OS X.
Supports ws/wss/polling connections and binary.
For socket.io 1.0+ and Swift 1.2.
For socket.io 1.0+ and Swift.
DESC
s.homepage = "https://github.com/socketio/socket.io-client-swift"
s.license = { :type => 'MIT' }
@@ -13,7 +14,7 @@ Pod::Spec.new do |s|
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.tvos.deployment_target = '9.0'
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v5.1.0' }
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v5.3.0' }
s.source_files = "Source/**/*.swift"
s.requires_arc = true
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
@@ -8,9 +8,9 @@
/* Begin PBXBuildFile section */
572EF21F1B51F16C00EEBB58 /* SocketIO-iOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 572EF21E1B51F16C00EEBB58 /* SocketIO-iOS.h */; settings = {ATTRIBUTES = (Public, ); }; };
572EF2251B51F16C00EEBB58 /* SocketIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 572EF2191B51F16C00EEBB58 /* SocketIO.framework */; };
572EF2251B51F16C00EEBB58 /* SocketIOClientSwift.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 572EF2191B51F16C00EEBB58 /* SocketIOClientSwift.framework */; };
572EF23D1B51F18A00EEBB58 /* SocketIO-Mac.h in Headers */ = {isa = PBXBuildFile; fileRef = 572EF23C1B51F18A00EEBB58 /* SocketIO-Mac.h */; settings = {ATTRIBUTES = (Public, ); }; };
572EF2431B51F18A00EEBB58 /* SocketIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 572EF2381B51F18A00EEBB58 /* SocketIO.framework */; };
572EF2431B51F18A00EEBB58 /* SocketIOClientSwift.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 572EF2381B51F18A00EEBB58 /* SocketIOClientSwift.framework */; };
57634A111BD9B46A00E19CD7 /* SocketIO-iOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 572EF21E1B51F16C00EEBB58 /* SocketIO-iOS.h */; settings = {ATTRIBUTES = (Public, ); }; };
57634A231BD9B46D00E19CD7 /* SocketSideEffectTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */; };
57634A2A1BD9B46D00E19CD7 /* SocketEngineTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */; };
@@ -159,12 +159,12 @@
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
572EF2191B51F16C00EEBB58 /* SocketIO.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SocketIO.framework; sourceTree = BUILT_PRODUCTS_DIR; };
572EF2191B51F16C00EEBB58 /* SocketIOClientSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SocketIOClientSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; };
572EF21D1B51F16C00EEBB58 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
572EF21E1B51F16C00EEBB58 /* SocketIO-iOS.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "SocketIO-iOS.h"; sourceTree = "<group>"; };
572EF2241B51F16C00EEBB58 /* SocketIO-iOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SocketIO-iOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
572EF22A1B51F16C00EEBB58 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
572EF2381B51F18A00EEBB58 /* SocketIO.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SocketIO.framework; sourceTree = BUILT_PRODUCTS_DIR; };
572EF2381B51F18A00EEBB58 /* SocketIOClientSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SocketIOClientSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; };
572EF23B1B51F18A00EEBB58 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
572EF23C1B51F18A00EEBB58 /* SocketIO-Mac.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "SocketIO-Mac.h"; sourceTree = "<group>"; };
572EF2421B51F18A00EEBB58 /* SocketIO-MacTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SocketIO-MacTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -213,7 +213,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
572EF2251B51F16C00EEBB58 /* SocketIO.framework in Frameworks */,
572EF2251B51F16C00EEBB58 /* SocketIOClientSwift.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -228,7 +228,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
572EF2431B51F18A00EEBB58 /* SocketIO.framework in Frameworks */,
572EF2431B51F18A00EEBB58 /* SocketIOClientSwift.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -265,9 +265,9 @@
572EF21A1B51F16C00EEBB58 /* Products */ = {
isa = PBXGroup;
children = (
572EF2191B51F16C00EEBB58 /* SocketIO.framework */,
572EF2191B51F16C00EEBB58 /* SocketIOClientSwift.framework */,
572EF2241B51F16C00EEBB58 /* SocketIO-iOSTests.xctest */,
572EF2381B51F18A00EEBB58 /* SocketIO.framework */,
572EF2381B51F18A00EEBB58 /* SocketIOClientSwift.framework */,
572EF2421B51F18A00EEBB58 /* SocketIO-MacTests.xctest */,
57634A161BD9B46A00E19CD7 /* SocketIO.framework */,
57634A3B1BD9B46D00E19CD7 /* SocketIO-tvOSTests.xctest */,
@@ -421,7 +421,7 @@
);
name = "SocketIO-iOS";
productName = "SocketIO-iOS";
productReference = 572EF2191B51F16C00EEBB58 /* SocketIO.framework */;
productReference = 572EF2191B51F16C00EEBB58 /* SocketIOClientSwift.framework */;
productType = "com.apple.product-type.framework";
};
572EF2231B51F16C00EEBB58 /* SocketIO-iOSTests */ = {
@@ -457,7 +457,7 @@
);
name = "SocketIO-Mac";
productName = "SocketIO-Mac";
productReference = 572EF2381B51F18A00EEBB58 /* SocketIO.framework */;
productReference = 572EF2381B51F18A00EEBB58 /* SocketIOClientSwift.framework */;
productType = "com.apple.product-type.framework";
};
572EF2411B51F18A00EEBB58 /* SocketIO-MacTests */ = {
@@ -798,7 +798,7 @@
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MACOSX_DEPLOYMENT_TARGET = 10.10;
ONLY_ACTIVE_ARCH = YES;
PRODUCT_NAME = SocketIO;
PRODUCT_NAME = SocketIOClientSwift;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
TVOS_DEPLOYMENT_TARGET = 9.0;
WATCHOS_DEPLOYMENT_TARGET = 2.0;
@@ -813,7 +813,7 @@
ENABLE_BITCODE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MACOSX_DEPLOYMENT_TARGET = 10.10;
PRODUCT_NAME = SocketIO;
PRODUCT_NAME = SocketIOClientSwift;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
TVOS_DEPLOYMENT_TARGET = 9.0;
WATCHOS_DEPLOYMENT_TARGET = 2.0;
@@ -866,7 +866,7 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_BUNDLE_IDENTIFIER = io.socket.SocketIOClientSwift;
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
@@ -916,7 +916,7 @@
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MTL_ENABLE_DEBUG_INFO = NO;
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_BUNDLE_IDENTIFIER = io.socket.SocketIOClientSwift;
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = "1,2";
@@ -15,7 +15,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -57,7 +57,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -79,7 +79,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -97,7 +97,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -15,7 +15,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -58,7 +58,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -80,7 +80,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -98,7 +98,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
+1 -1
View File
@@ -7,7 +7,7 @@
//
import XCTest
@testable import SocketIO
@testable import SocketIOClientSwift
class SocketAckManagerTest: XCTestCase {
var ackManager = SocketAckManager()
@@ -7,7 +7,7 @@
//
import XCTest
@testable import SocketIO
@testable import SocketIOClientSwift
class SocketBasicPacketTest: XCTestCase {
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
+3 -3
View File
@@ -7,7 +7,7 @@
//
import XCTest
@testable import SocketIO
@testable import SocketIOClientSwift
class SocketEngineTest: XCTestCase {
var client: SocketIOClient!
@@ -15,8 +15,8 @@ class SocketEngineTest: XCTestCase {
override func setUp() {
super.setUp()
client = SocketIOClient(socketURL: "")
engine = SocketEngine(client: client, url: "", options: nil)
client = SocketIOClient(socketURL: NSURL(string: "http://localhost")!)
engine = SocketEngine(client: client, url: NSURL(string: "http://localhost")!, options: nil)
client.setTestable()
}
@@ -7,7 +7,7 @@
//
import XCTest
@testable import SocketIO
@testable import SocketIOClientSwift
class SocketNamespacePacketTest: XCTestCase {
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
+2 -2
View File
@@ -7,10 +7,10 @@
//
import XCTest
@testable import SocketIO
@testable import SocketIOClientSwift
class SocketParserTest: XCTestCase {
let testSocket = SocketIOClient(socketURL: "")
let testSocket = SocketIOClient(socketURL: NSURL())
//Format key: message; namespace-data-binary-id
static let packetTypes: Dictionary<String, (String, [AnyObject], [NSData], Int)> = [
+2 -2
View File
@@ -7,7 +7,7 @@
//
import XCTest
@testable import SocketIO
@testable import SocketIOClientSwift
class SocketSideEffectTest: XCTestCase {
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
@@ -16,7 +16,7 @@ class SocketSideEffectTest: XCTestCase {
override func setUp() {
super.setUp()
socket = SocketIOClient(socketURL: "")
socket = SocketIOClient(socketURL: NSURL())
socket.setTestable()
}
+2 -2
View File
@@ -24,8 +24,8 @@
import Foundation
@objc public final class SocketAnyEvent: NSObject {
public let event: String!
public final class SocketAnyEvent: NSObject {
public let event: String
public let items: NSArray?
override public var description: String {
return "SocketAnyEvent: Event: \(event) items: \(items ?? nil)"
+65 -65
View File
@@ -29,6 +29,11 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
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: AnyObject]? {
didSet {
(urlPolling, urlWebSocket) = createURLs()
}
}
public var postWait = [String]()
public var waitingForPoll = false
public var waitingForPost = false
@@ -46,9 +51,9 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
public private(set) var probing = false
public private(set) var session: NSURLSession?
public private(set) var sid = ""
public private(set) var socketPath = "/engine.io"
public private(set) var urlPolling = ""
public private(set) var urlWebSocket = ""
public private(set) var socketPath = "/engine.io/"
public private(set) var urlPolling = NSURL()
public private(set) var urlWebSocket = NSURL()
public private(set) var websocket = false
public private(set) var ws: WebSocket?
@@ -59,11 +64,9 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
private typealias Probe = (msg: String, type: SocketEnginePacketType, data: [NSData])
private typealias ProbeWaitQueue = [Probe]
private let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
private let logType = "SocketEngine"
private let url: String
private let url: NSURL
private var connectParams: [String: AnyObject]?
private var pingInterval: Double?
private var pingTimeout = 0.0 {
didSet {
@@ -76,13 +79,15 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
private var secure = false
private var selfSigned = false
private var voipEnabled = false
public init(client: SocketEngineClient, url: String, options: Set<SocketIOClientOption>) {
public init(client: SocketEngineClient, url: NSURL, options: Set<SocketIOClientOption>) {
self.client = client
self.url = url
for option in options {
switch option {
case let .ConnectParams(params):
connectParams = params
case let .SessionDelegate(delegate):
sessionDelegate = delegate
case let .ForcePolling(force):
@@ -105,15 +110,30 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
continue
}
}
super.init()
(urlPolling, urlWebSocket) = createURLs()
}
public convenience init(client: SocketEngineClient, url: String, options: NSDictionary?) {
self.init(client: client, url: url,
options: options?.toSocketOptionsSet() ?? [])
public convenience init(client: SocketEngineClient, url: NSURL, options: NSDictionary?) {
self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? [])
}
@available(*, deprecated=5.3)
public convenience init(client: SocketEngineClient, urlString: String, options: Set<SocketIOClientOption>) {
guard let url = NSURL(string: urlString) else { fatalError("Incorrect url") }
self.init(client: client, url: url, options: options)
}
@available(*, deprecated=5.3)
public convenience init(client: SocketEngineClient, urlString: String, options: NSDictionary?) {
guard let url = NSURL(string: urlString) else { fatalError("Incorrect url") }
self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Engine is being deinit", type: logType)
DefaultSocketLogger.Logger.log("Engine is being released", type: logType)
closed = true
stopPolling()
}
@@ -131,7 +151,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
switch code {
case 0: // Unknown transport
didError(error)
case 1: // Unknown sid. clear and retry connect
case 1: // Unknown sid.
didError(error)
case 2: // Bad handshake request
didError(error)
@@ -188,49 +208,42 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
}
private func createURLs(params: [String: AnyObject]?) -> (String, String) {
private func createURLs() -> (NSURL, NSURL) {
if client == nil {
return ("", "")
return (NSURL(), NSURL())
}
let socketURL = "\(url)\(socketPath)/?transport="
var urlPolling: String
var urlWebSocket: String
let urlPolling = NSURLComponents(string: url.absoluteString)!
let urlWebSocket = NSURLComponents(string: url.absoluteString)!
var queryString = ""
urlWebSocket.path = socketPath
urlPolling.path = socketPath
urlWebSocket.query = "transport=websocket"
urlPolling.query = "transport=polling&b64=1"
if secure {
urlPolling = "https://" + socketURL + "polling"
urlWebSocket = "wss://" + socketURL + "websocket"
urlPolling.scheme = "https"
urlWebSocket.scheme = "wss"
} else {
urlPolling = "http://" + socketURL + "polling"
urlWebSocket = "ws://" + socketURL + "websocket"
urlPolling.scheme = "http"
urlWebSocket.scheme = "ws"
}
if params != nil {
for (key, value) in params! {
let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
urlPolling += "&\(keyEsc)="
urlWebSocket += "&\(keyEsc)="
if value is String {
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
urlPolling += "\(valueEsc)"
urlWebSocket += "\(valueEsc)"
} else {
urlPolling += "\(value)"
urlWebSocket += "\(value)"
}
if connectParams != nil {
for (key, value) in connectParams! {
queryString += "&\(key)=\(value)"
}
}
return (urlPolling, urlWebSocket)
urlWebSocket.query = urlWebSocket.query! + queryString
urlPolling.query = urlPolling.query! + queryString
return (urlPolling.URL!, urlWebSocket.URL!)
}
private func createWebsocketAndConnect(connect: Bool) {
let wsUrl = urlWebSocket + (sid == "" ? "" : "&sid=\(sid)")
ws = WebSocket(url: NSURL(string: wsUrl)!)
private func createWebsocketAndConnect() {
ws = WebSocket(url: urlWebSocketWithSid)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
@@ -250,9 +263,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
ws?.delegate = self
ws?.selfSignedSSL = selfSigned
if connect {
ws?.connect()
}
ws?.connect()
}
public func didError(error: String) {
@@ -338,7 +349,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
if !forcePolling && !forceWebsockets && upgradeWs {
createWebsocketAndConnect(true)
createWebsocketAndConnect()
}
@@ -365,30 +376,26 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
}
public func open(opts: [String: AnyObject]?) {
public func open() {
if connected {
DefaultSocketLogger.Logger.error("Engine tried opening while connected. This is probably a programming error. "
+ "Abandoning open attempt", type: logType)
return
}
connectParams = opts
DefaultSocketLogger.Logger.log("Starting engine", type: logType)
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
resetEngine()
(urlPolling, urlWebSocket) = createURLs(opts)
if forceWebsockets {
polling = false
websocket = true
createWebsocketAndConnect(true)
createWebsocketAndConnect()
return
}
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
let reqPolling = NSMutableURLRequest(URL: urlPolling)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
@@ -460,15 +467,6 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
waitingForPost = false
websocket = false
}
/// Send an engine message (4)
public func send(msg: String, withData datas: [NSData]) {
if probing {
probeWait.append((msg, .Message, datas))
} else {
write(msg, withType: .Message, withData: datas)
}
}
@objc private func sendPing() {
//Server is not responding
@@ -516,10 +514,12 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
DefaultSocketLogger.Logger.log("Writing ws: %@ has data: %@",
type: self.logType, args: msg, data.count != 0)
self.sendWebSocketMessage(msg, withType: type, withData: data)
} else {
} else if !self.probing {
DefaultSocketLogger.Logger.log("Writing poll: %@ has data: %@",
type: self.logType, args: msg, data.count != 0)
self.sendPollMessage(msg, withType: type, withData: data)
} else {
self.probeWait.append((msg, type, data))
}
}
}
+3 -3
View File
@@ -71,7 +71,7 @@ extension SocketEnginePollable {
postWait.removeAll(keepCapacity: false)
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&sid=\(sid)")!)
let req = NSMutableURLRequest(URL: urlPollingWithSid)
addHeaders(req)
@@ -93,7 +93,7 @@ extension SocketEnginePollable {
}
waitingForPoll = true
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&sid=\(sid)&b64=1")!)
let req = NSMutableURLRequest(URL: urlPollingWithSid)
addHeaders(req)
doLongPoll(req)
@@ -112,7 +112,7 @@ extension SocketEnginePollable {
func doLongPoll(req: NSURLRequest) {
doRequest(req) {[weak self] data, res, err in
guard let this = self else {return}
guard let this = self else { return }
if err != nil || data == nil {
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
+25 -7
View File
@@ -29,6 +29,7 @@ import Foundation
weak var client: SocketEngineClient? { get set }
var closed: Bool { get }
var connected: Bool { get }
var connectParams: [String: AnyObject]? { get set }
var cookies: [NSHTTPCookie]? { get }
var extraHeaders: [String: String]? { get }
var fastUpgrade: Bool { get }
@@ -42,28 +43,40 @@ import Foundation
var handleQueue: dispatch_queue_t! { get }
var sid: String { get }
var socketPath: String { get }
var urlPolling: String { get }
var urlWebSocket: String { get }
var urlPolling: NSURL { get }
var urlWebSocket: NSURL { get }
var websocket: Bool { get }
init(client: SocketEngineClient, url: String, options: NSDictionary?)
init(client: SocketEngineClient, url: NSURL, options: NSDictionary?)
func close(reason: String)
func didError(error: String)
func doFastUpgrade()
func flushWaitingForPostToWebSocket()
func open(opts: [String: AnyObject]?)
func open()
func parseEngineData(data: NSData)
func parseEngineMessage(message: String, fromPolling: Bool)
func send(msg: String, withData datas: [NSData])
func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData])
}
extension SocketEngineSpec {
var urlPollingWithSid: NSURL {
let com = NSURLComponents(URL: urlPolling, resolvingAgainstBaseURL: false)!
com.query = com.query! + "&sid=\(sid)"
return com.URL!
}
var urlWebSocketWithSid: NSURL {
let com = NSURLComponents(URL: urlWebSocket, resolvingAgainstBaseURL: false)!
com.query = com.query! + (sid == "" ? "" : "&sid=\(sid)")
return com.URL!
}
func createBinaryDataForSend(data: NSData) -> Either<NSData, String> {
if websocket {
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
byteArray[0] = 4
var byteArray = [UInt8](count: 1, repeatedValue: 0x4)
let mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.appendData(data)
@@ -75,4 +88,9 @@ extension SocketEngineSpec {
return .Right(str)
}
}
/// Send an engine message (4)
func send(msg: String, withData datas: [NSData]) {
write(msg, withType: .Message, withData: datas)
}
}
+141 -131
View File
@@ -25,12 +25,11 @@
import Foundation
public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable {
public let socketURL: String
public let socketURL: NSURL
public private(set) var engine: SocketEngineSpec?
public private(set) var status = SocketIOClientStatus.NotConnected
public var connectParams: [String: AnyObject]?
public var forceNew = false
public var nsp = "/"
public var options: Set<SocketIOClientOption>
@@ -39,39 +38,36 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
public var sid: String? {
return engine?.sid
}
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
private let logType = "SocketIOClient"
private let parseQueue = dispatch_queue_create("com.socketio.parseQueue", DISPATCH_QUEUE_SERIAL)
private var anyHandler: ((SocketAnyEvent) -> Void)?
private var currentReconnectAttempt = 0
private var handlers = [SocketEventHandler]()
private var reconnectTimer: NSTimer?
private var ackHandlers = SocketAckManager()
private(set) var currentAck = -1
private(set) var handleQueue = dispatch_get_main_queue()
private(set) var reconnectAttempts = -1
var waitingData = [SocketPacket]()
/**
Type safe way to create a new SocketIOClient. opts can be omitted
*/
public init(socketURL: String, options: Set<SocketIOClientOption> = []) {
public init(socketURL: NSURL, options: Set<SocketIOClientOption> = []) {
self.options = options
self.socketURL = socketURL
if socketURL["https://"].matches().count != 0 {
if socketURL.absoluteString.hasPrefix("https://") {
self.options.insertIgnore(.Secure(true))
}
self.socketURL = socketURL["https?://"] ~= ""
for option in options {
switch option {
case let .ConnectParams(params):
connectParams = params
case let .Reconnects(reconnects):
self.reconnects = reconnects
case let .ReconnectAttempts(attempts):
@@ -93,99 +89,111 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
}
self.options.insertIgnore(.Path("/socket.io"))
self.options.insertIgnore(.Path("/socket.io/"))
super.init()
}
/**
Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity.
If using Swift it's recommended to use `init(var socketURL: String, opts: SocketOptionsDictionary? = nil)`
If using Swift it's recommended to use `init(socketURL: NSURL, options: Set<SocketIOClientOption>)`
*/
public convenience init(socketURL: String, options: NSDictionary?) {
self.init(socketURL: socketURL,
options: options?.toSocketOptionsSet() ?? [])
public convenience init(socketURL: NSURL, options: NSDictionary?) {
self.init(socketURL: socketURL, options: options?.toSocketOptionsSet() ?? [])
}
/// Please use the NSURL based init
@available(*, deprecated=5.3)
public convenience init(socketURLString: String, options: Set<SocketIOClientOption> = []) {
guard let url = NSURL(string: socketURLString) else { fatalError("Incorrect url") }
self.init(socketURL: url, options: options)
}
/// Please use the NSURL based init
@available(*, deprecated=5.3)
public convenience init(socketURLString: String, options: NSDictionary?) {
guard let url = NSURL(string: socketURLString) else { fatalError("Incorrect url") }
self.init(socketURL: url, options: options?.toSocketOptionsSet() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Client is being deinit", type: logType)
DefaultSocketLogger.Logger.log("Client is being released", type: logType)
engine?.close("Client Deinit")
}
private func addEngine() -> SocketEngineSpec {
DefaultSocketLogger.Logger.log("Adding engine", type: logType)
engine = SocketEngine(client: self, url: socketURL, options: options)
return engine!
}
private func clearReconnectTimer() {
reconnectTimer?.invalidate()
reconnectTimer = nil
}
@available(*, deprecated=6.0)
@available(*, deprecated=5.3)
public func close() {
disconnect()
}
/**
Connect to the server.
*/
public func connect() {
connect(timeoutAfter: 0, withTimeoutHandler: nil)
}
/**
Connect to the server. If we aren't connected after timeoutAfter, call handler
*/
public func connect(timeoutAfter timeoutAfter: Int,
withTimeoutHandler handler: (() -> Void)?) {
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
guard status != .Connected else {
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket",
type: logType)
return
}
status = .Connecting
if engine == nil || forceNew {
addEngine().open(connectParams)
} else {
engine?.open(connectParams)
}
guard timeoutAfter != 0 else { return }
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
dispatch_after(time, handleQueue) {[weak self] in
if let this = self where this.status != .Connected {
this.status = .Closed
this.engine?.close("Connect timeout")
handler?()
}
public func connect(timeoutAfter timeoutAfter: Int, withTimeoutHandler handler: (() -> Void)?) {
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
guard status != .Connected else {
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket",
type: logType)
return
}
status = .Connecting
if engine == nil || forceNew {
addEngine().open()
} else {
engine?.open()
}
guard timeoutAfter != 0 else { return }
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
dispatch_after(time, handleQueue) {[weak self] in
if let this = self where this.status != .Connected {
this.status = .Closed
this.engine?.close("Connect timeout")
handler?()
}
}
}
private func createOnAck(items: [AnyObject]) -> OnAckCallback {
currentAck += 1
return {[weak self, ack = currentAck] timeout, callback in
if let this = self {
this.ackHandlers.addAck(ack, callback: callback)
dispatch_async(this.emitQueue) {
this._emit(items, ack: ack)
}
if timeout != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
dispatch_after(time, this.handleQueue) {
this.ackHandlers.timeoutAck(ack)
}
@@ -193,51 +201,51 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
}
}
func didConnect() {
DefaultSocketLogger.Logger.log("Socket connected", type: logType)
status = .Connected
currentReconnectAttempt = 0
clearReconnectTimer()
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
handleEvent("connect", data: [], isInternalMessage: false)
}
func didDisconnect(reason: String) {
guard status != .Closed else {
return
}
DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason)
status = .Closed
reconnects = false
// Make sure the engine is actually dead.
engine?.close("Client closed")
engine?.close(reason)
handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
/**
Closes the socket. Only reopen the same socket if you know what you're doing.
Disconnects the socket. Only reconnect the same socket if you know what you're doing.
Will turn off automatic reconnects.
*/
public func disconnect() {
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
reconnects = false
didDisconnect("Closed")
didDisconnect("Disconnect")
}
/**
Send a message to the server
*/
public func emit(event: String, _ items: AnyObject...) {
emit(event, withItems: items)
}
/**
Same as emit, but meant for Objective-C
*/
@@ -246,12 +254,12 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
handleEvent("error", data: ["Tried emitting \(event) when not connected"], isInternalMessage: true)
return
}
dispatch_async(emitQueue) {
self._emit([event] + items)
}
}
/**
Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
an ack.
@@ -259,45 +267,45 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
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, withItems items: [AnyObject]) -> OnAckCallback {
return createOnAck([event] + items)
}
private func _emit(data: [AnyObject], ack: Int? = nil) {
guard status == .Connected else {
handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
return
}
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting: %@", type: logType, args: str)
engine?.send(str, withData: packet.binary)
}
// If the server wants to know that the client received data
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) {
waitingData.removeAll()
if status == .Closed || !reconnects {
didDisconnect(reason)
} else if status != .Reconnecting {
@@ -306,23 +314,23 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
tryReconnect()
}
}
/// error
public func engineDidError(reason: String) {
DefaultSocketLogger.Logger.error("%@", type: logType, args: reason)
handleEvent("error", data: [reason], isInternalMessage: true)
}
// Called when the socket gets an ack for something it sent
func handleAck(ack: Int, data: [AnyObject]) {
guard status == .Connected else {return}
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
ackHandlers.executeAck(ack, items: data)
}
/**
Causes an event to be handled. Only use if you know what you're doing.
*/
@@ -330,18 +338,18 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
guard status == .Connected || isInternalMessage else {
return
}
DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data ?? "")
dispatch_async(handleQueue) {
self.anyHandler?(SocketAnyEvent(event: event, items: data))
for handler in self.handlers where handler.event == event {
handler.executeCallback(data, withAck: ack, withSocket: self)
}
}
}
/**
Leaves nsp and goes back to /
*/
@@ -351,104 +359,106 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
nsp = "/"
}
}
/**
Joins namespace
*/
public func joinNamespace(namespace: String) {
nsp = namespace
if nsp != "/" {
DefaultSocketLogger.Logger.log("Joining namespace", type: logType)
engine?.send("0\(nsp)", withData: [])
}
}
/**
Removes handler(s)
*/
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 id: NSUUID) {
DefaultSocketLogger.Logger.log("Removing handler with id: %@", type: logType, args: id)
handlers = handlers.filter { $0.id != id }
}
/**
Adds a handler for an event.
Returns: A unique id for the handler
*/
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: NSUUID(), callback: callback)
handlers.append(handler)
return handler.id
}
/**
Adds a single-use handler for an event.
Returns: A unique id for the handler
*/
public func once(event: String, callback: NormalCallback) -> NSUUID {
DefaultSocketLogger.Logger.log("Adding once handler for event: %@", type: logType, args: event)
let id = NSUUID()
let handler = SocketEventHandler(event: event, id: id) {[weak self] data, ack in
guard let this = self else {return}
guard let this = self else { return }
this.off(id: id)
callback(data, ack)
}
handlers.append(handler)
return handler.id
}
/**
Adds a handler that will be called on every event.
*/
public func onAny(handler: (SocketAnyEvent) -> Void) {
anyHandler = handler
}
/**
Same as connect
*/
@available(*, deprecated=5.3)
public func open() {
connect()
}
public func parseEngineMessage(msg: String) {
DefaultSocketLogger.Logger.log("Should parse message", type: "SocketIOClient")
DefaultSocketLogger.Logger.log("Should parse message: %@", type: "SocketIOClient", args: msg)
dispatch_async(parseQueue) {
self.parseSocketMessage(msg)
}
}
public func parseEngineBinaryData(data: NSData) {
dispatch_async(parseQueue) {
self.parseBinaryData(data)
}
}
/**
Tries to reconnect to the server.
*/
public func reconnect() {
tryReconnect()
}
/**
Removes all handlers.
Can be used after disconnecting to break any potential remaining retain cycles.
@@ -456,38 +466,38 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
public func removeAllHandlers() {
handlers.removeAll(keepCapacity: false)
}
private func tryReconnect() {
if reconnectTimer == nil {
DefaultSocketLogger.Logger.log("Starting reconnect", type: logType)
status = .Reconnecting
dispatch_async(dispatch_get_main_queue()) {
self.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self.reconnectWait),
target: self, selector: "_tryReconnect", userInfo: nil, repeats: true)
}
}
}
@objc private func _tryReconnect() {
if status == .Connected {
clearReconnectTimer()
return
}
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
clearReconnectTimer()
didDisconnect("Reconnect Failed")
return
}
DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType)
handleEvent("reconnectAttempt", data: [reconnectAttempts - currentReconnectAttempt],
isInternalMessage: true)
currentReconnectAttempt += 1
connect()
}
@@ -498,15 +508,15 @@ extension SocketIOClient {
var testHandlers: [SocketEventHandler] {
return handlers
}
func setTestable() {
status = .Connected
}
func setTestEngine(engine: SocketEngineSpec?) {
self.engine = engine
}
func emitTest(event: String, _ data: AnyObject...) {
self._emit([event] + data)
}
+1 -1
View File
@@ -106,7 +106,7 @@ struct SocketPacket {
type: SocketPacket.logType)
}
} else if let str = arg as? String {
restOfMessage += "\"" + ((str["\n"] ~= "\\\\n")["\r"] ~= "\\\\r") + "\","
restOfMessage += "\"" + ((str["\n"] <~ "\\\\n")["\r"] <~ "\\\\r") + "\","
} else if arg is NSNull {
restOfMessage += "null,"
} else {
+2 -2
View File
@@ -58,7 +58,7 @@ extension SocketParsable {
case .Disconnect:
didDisconnect("Got Disconnect")
case .Error:
handleEvent("error", data: pack.data, isInternalMessage: false, withAck: pack.id)
handleEvent("error", data: pack.data, isInternalMessage: true, withAck: pack.id)
default:
DefaultSocketLogger.Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description)
}
@@ -112,7 +112,7 @@ extension SocketParsable {
}
let d = message[parser.currentIndex.advancedBy(1)..<message.endIndex]
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] <~ "\"~~$2\""
switch parseData(noPlaceholders) {
case let .Left(err):
+12 -31
View File
@@ -13,13 +13,20 @@
import Foundation
infix operator <~ { associativity none precedence 130 }
private let lock = dispatch_semaphore_create(1)
private var swiftRegexCache = [String: NSRegularExpression]()
internal class SwiftRegex: NSObject, BooleanType {
internal final class SwiftRegex: NSObject, BooleanType {
var target:String
var regex: NSRegularExpression
init(target:String, pattern:String, options:NSRegularExpressionOptions?) {
if dispatch_semaphore_wait(lock, dispatch_time(DISPATCH_TIME_NOW, Int64(10 * NSEC_PER_MSEC))) != 0 {
fatalError("This should never happen")
}
self.target = target
if let regex = swiftRegexCache[pattern] {
self.regex = regex
@@ -34,6 +41,7 @@ internal class SwiftRegex: NSObject, BooleanType {
self.regex = NSRegularExpression()
}
}
dispatch_semaphore_signal(lock)
super.init()
}
@@ -41,11 +49,11 @@ internal class SwiftRegex: NSObject, BooleanType {
fatalError("SwiftRegex: \(message)")
}
private final var targetRange: NSRange {
private var targetRange: NSRange {
return NSRange(location: 0,length: target.utf16.count)
}
private final func substring(range: NSRange) -> String? {
private func substring(range: NSRange) -> String? {
if range.location != NSNotFound {
return (target as NSString).substringWithRange(range)
} else {
@@ -168,36 +176,9 @@ extension String {
}
}
func ~= (left: SwiftRegex, right: String) -> String {
func <~ (left: SwiftRegex, right: String) -> String {
return left.substituteMatches({match, stop in
return left.regex.replacementStringForResult( match,
inString: left.target as String, offset: 0, template: right )
}, options: [])
}
func ~= (left: SwiftRegex, right: [String]) -> String {
var matchNumber = 0
return left.substituteMatches({match, stop -> String in
if ++matchNumber == right.count {
stop.memory = true
}
return left.regex.replacementStringForResult( match,
inString: left.target as String, offset: 0, template: right[matchNumber-1] )
}, options: [])
}
func ~= (left: SwiftRegex, right: (String) -> String) -> String {
// return right(left.substring(match.range))
return left.substituteMatches(
{match, stop -> String in
right(left.substring(match.range)!)
}, options: [])
}
func ~= (left: SwiftRegex, right: ([String]?) -> String) -> String {
return left.substituteMatches({match, stop -> String in
return right(left.groupsForMatch(match))
}, options: [])
}
+1
View File
@@ -382,6 +382,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
inputQueue = inputQueue.filter{$0 != data}
dequeueInput()
}
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]