Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31e4c60db8 | ||
|
|
ab536e2279 | ||
|
|
3401414430 | ||
|
|
50216647ca | ||
|
|
98063c8bf7 | ||
|
|
9747cc4ddc | ||
|
|
7e23597351 | ||
|
|
437c0880e8 | ||
|
|
c237197b8c | ||
|
|
4ea3f40ca7 | ||
|
|
a24b54c18f | ||
|
|
2377c8b45f | ||
|
|
e02ca23d14 | ||
|
|
18285f5401 | ||
|
|
1c80cc7e4c | ||
|
|
0959dd35d7 | ||
|
|
5d23270d70 | ||
|
|
2b4b5bf407 | ||
|
|
84cb635f11 | ||
|
|
119b479be2 | ||
|
|
9ff90f511e | ||
|
|
82e7882497 | ||
|
|
8e1434e63b | ||
|
|
44ee94d2ac | ||
|
|
6efeb7d5b2 | ||
|
|
e1865e3f94 | ||
|
|
1b4b571be6 | ||
|
|
c9f653ef2c | ||
|
|
3073130598 | ||
|
|
ed3d49001f | ||
|
|
4ee196c5fb | ||
|
|
baca9fc8da | ||
|
|
1a5ac74984 | ||
|
|
6c779e84d2 | ||
|
|
293d71bf97 | ||
|
|
2f1f77141e | ||
|
|
d4c01183ab | ||
|
|
5d81377e0a | ||
|
|
8f8d5acdba | ||
|
|
a0167ae213 | ||
|
|
4f5837afa7 | ||
|
|
718caba9d9 |
No files matched your search
+1
-1
@@ -1,7 +1,7 @@
|
||||
language: objective-c
|
||||
xcode_project: Socket.IO-Client-Swift.xcodeproj # path to your xcodeproj folder
|
||||
xcode_scheme: SocketIO-iOS
|
||||
osx_image: xcode7
|
||||
osx_image: xcode7.3
|
||||
before_install:
|
||||
- cd Socket.IO-Test-Server/
|
||||
- npm install
|
||||
|
||||
@@ -77,7 +77,7 @@ import PackageDescription
|
||||
let package = Package(
|
||||
name: "YourSocketIOProject",
|
||||
dependencies: [
|
||||
.Package(url: "https://github.com/socketio/socket.io-client-swift", majorVersion: 5)
|
||||
.Package(url: "https://github.com/socketio/socket.io-client-swift", majorVersion: 6)
|
||||
]
|
||||
)
|
||||
```
|
||||
@@ -88,7 +88,7 @@ Carthage
|
||||
-----------------
|
||||
Add this line to your `Cartfile`:
|
||||
```
|
||||
github "socketio/socket.io-client-swift" ~> 6.0.0 # Or latest version
|
||||
github "socketio/socket.io-client-swift" ~> 6.1.2 # Or latest version
|
||||
```
|
||||
|
||||
Run `carthage update --platform ios,macosx`.
|
||||
@@ -102,7 +102,7 @@ source 'https://github.com/CocoaPods/Specs.git'
|
||||
platform :ios, '8.0'
|
||||
use_frameworks!
|
||||
|
||||
pod 'Socket.IO-Client-Swift', '~> 6.0.0' # Or latest version
|
||||
pod 'Socket.IO-Client-Swift', '~> 6.1.2' # Or latest version
|
||||
```
|
||||
|
||||
Install pods:
|
||||
@@ -130,7 +130,7 @@ CocoaSeeds
|
||||
Add this line to your `Seedfile`:
|
||||
|
||||
```
|
||||
github "socketio/socket.io-client-swift", "v6.0.0", :files => "Source/*.swift" # Or latest version
|
||||
github "socketio/socket.io-client-swift", "v6.1.2", :files => "Source/*.swift" # Or latest version
|
||||
```
|
||||
|
||||
Run `seed install`.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "Socket.IO-Client-Swift"
|
||||
s.module_name = "SocketIOClientSwift"
|
||||
s.version = "6.0.0"
|
||||
s.version = "6.1.2"
|
||||
s.summary = "Socket.IO-client for iOS and OS X"
|
||||
s.description = <<-DESC
|
||||
Socket.IO-client for iOS and OS X.
|
||||
@@ -14,7 +14,7 @@ Pod::Spec.new do |s|
|
||||
s.ios.deployment_target = '8.0'
|
||||
s.osx.deployment_target = '10.10'
|
||||
s.tvos.deployment_target = '9.0'
|
||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v6.0.0' }
|
||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v6.1.2' }
|
||||
s.source_files = "Source/**/*.swift"
|
||||
s.requires_arc = true
|
||||
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
|
||||
|
||||
@@ -101,11 +101,6 @@
|
||||
74171EC51C10CD240062D398 /* SocketTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E601C10CD240062D398 /* SocketTypes.swift */; };
|
||||
74171EC71C10CD240062D398 /* SocketTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E601C10CD240062D398 /* SocketTypes.swift */; };
|
||||
74171EC81C10CD240062D398 /* SocketTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E601C10CD240062D398 /* SocketTypes.swift */; };
|
||||
74171EC91C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; };
|
||||
74171ECA1C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; };
|
||||
74171ECB1C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; };
|
||||
74171ECD1C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; };
|
||||
74171ECE1C10CD240062D398 /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E611C10CD240062D398 /* SwiftRegex.swift */; };
|
||||
74171ECF1C10CD240062D398 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E621C10CD240062D398 /* WebSocket.swift */; };
|
||||
74171ED01C10CD240062D398 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E621C10CD240062D398 /* WebSocket.swift */; };
|
||||
74171ED11C10CD240062D398 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E621C10CD240062D398 /* WebSocket.swift */; };
|
||||
@@ -116,17 +111,24 @@
|
||||
7420CB791C49629E00956AA4 /* SocketEnginePollable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */; };
|
||||
7420CB7A1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */; };
|
||||
7420CB7B1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */; };
|
||||
742D150C1CA5794B00BD987D /* SocketObjectiveCTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 742D150B1CA5794B00BD987D /* SocketObjectiveCTest.m */; };
|
||||
74321DCB1C2D939A00CF6F43 /* SocketAckManagerTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74321DC91C2D939A00CF6F43 /* SocketAckManagerTest.swift */; };
|
||||
74321DCC1C2D939A00CF6F43 /* SocketParserTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74321DCA1C2D939A00CF6F43 /* SocketParserTest.swift */; };
|
||||
7471CCEA1C39926300364B59 /* SocketClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketClientSpec.swift */; };
|
||||
7471CCEB1C39926C00364B59 /* SocketClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketClientSpec.swift */; };
|
||||
7471CCEA1C39926300364B59 /* SocketIOClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */; };
|
||||
7471CCEB1C39926C00364B59 /* SocketIOClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */; };
|
||||
7472C65C1BCAB53E003CA70D /* SocketNamespacePacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */; };
|
||||
7472C65D1BCAB53E003CA70D /* SocketNamespacePacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */; };
|
||||
7472C65F1BCAC46E003CA70D /* SocketSideEffectTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */; };
|
||||
7472C6601BCAC46E003CA70D /* SocketSideEffectTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */; };
|
||||
74ABF7771C3991C10078C657 /* SocketClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketClientSpec.swift */; };
|
||||
74ABF7771C3991C10078C657 /* SocketIOClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */; };
|
||||
74F124F01BC574CF002966F4 /* SocketBasicPacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */; };
|
||||
74F124F11BC574CF002966F4 /* SocketBasicPacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */; };
|
||||
CEBA56961CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */; };
|
||||
CEBA56971CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */; };
|
||||
CEBA56981CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */; };
|
||||
CEBA569A1CDA0B8200BA0389 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* String.swift */; };
|
||||
CEBA569B1CDA0B8200BA0389 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* String.swift */; };
|
||||
CEBA569C1CDA0B8200BA0389 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* String.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@@ -183,16 +185,18 @@
|
||||
74171E5E1C10CD240062D398 /* SocketParsable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketParsable.swift; path = Source/SocketParsable.swift; sourceTree = "<group>"; };
|
||||
74171E5F1C10CD240062D398 /* SocketStringReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketStringReader.swift; path = Source/SocketStringReader.swift; sourceTree = "<group>"; };
|
||||
74171E601C10CD240062D398 /* SocketTypes.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketTypes.swift; path = Source/SocketTypes.swift; sourceTree = "<group>"; };
|
||||
74171E611C10CD240062D398 /* SwiftRegex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SwiftRegex.swift; path = Source/SwiftRegex.swift; sourceTree = "<group>"; };
|
||||
74171E621C10CD240062D398 /* WebSocket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = Source/WebSocket.swift; sourceTree = "<group>"; };
|
||||
741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketEngineTest.swift; sourceTree = "<group>"; };
|
||||
7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketEnginePollable.swift; path = Source/SocketEnginePollable.swift; sourceTree = "<group>"; };
|
||||
742D150B1CA5794B00BD987D /* SocketObjectiveCTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SocketObjectiveCTest.m; sourceTree = "<group>"; };
|
||||
74321DC91C2D939A00CF6F43 /* SocketAckManagerTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SocketAckManagerTest.swift; sourceTree = "<group>"; };
|
||||
74321DCA1C2D939A00CF6F43 /* SocketParserTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SocketParserTest.swift; sourceTree = "<group>"; };
|
||||
7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketNamespacePacketTest.swift; sourceTree = "<group>"; };
|
||||
7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketSideEffectTest.swift; sourceTree = "<group>"; };
|
||||
74ABF7761C3991C10078C657 /* SocketClientSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketClientSpec.swift; path = Source/SocketClientSpec.swift; sourceTree = "<group>"; };
|
||||
74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClientSpec.swift; path = Source/SocketIOClientSpec.swift; sourceTree = "<group>"; };
|
||||
74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketBasicPacketTest.swift; sourceTree = "<group>"; };
|
||||
CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = NSCharacterSet.swift; path = Source/NSCharacterSet.swift; sourceTree = "<group>"; };
|
||||
CEBA56991CDA0B8200BA0389 /* String.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = String.swift; path = Source/String.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -326,6 +330,7 @@
|
||||
74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */,
|
||||
741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */,
|
||||
7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */,
|
||||
742D150B1CA5794B00BD987D /* SocketObjectiveCTest.m */,
|
||||
74321DCA1C2D939A00CF6F43 /* SocketParserTest.swift */,
|
||||
7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */,
|
||||
572EF2471B51F18A00EEBB58 /* Supporting Files */,
|
||||
@@ -344,10 +349,10 @@
|
||||
5764DF7B1B51F24A004FF46E /* Source */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
CEBA569E1CDA0C0C00BA0389 /* utils */,
|
||||
74171E501C10CD240062D398 /* SocketAckEmitter.swift */,
|
||||
74171E511C10CD240062D398 /* SocketAckManager.swift */,
|
||||
74171E521C10CD240062D398 /* SocketAnyEvent.swift */,
|
||||
74ABF7761C3991C10078C657 /* SocketClientSpec.swift */,
|
||||
74171E531C10CD240062D398 /* SocketEngine.swift */,
|
||||
74171E541C10CD240062D398 /* SocketEngineClient.swift */,
|
||||
74171E551C10CD240062D398 /* SocketEnginePacketType.swift */,
|
||||
@@ -357,18 +362,27 @@
|
||||
74171E571C10CD240062D398 /* SocketEventHandler.swift */,
|
||||
74171E591C10CD240062D398 /* SocketIOClient.swift */,
|
||||
74171E5A1C10CD240062D398 /* SocketIOClientOption.swift */,
|
||||
74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */,
|
||||
74171E5B1C10CD240062D398 /* SocketIOClientStatus.swift */,
|
||||
74171E5C1C10CD240062D398 /* SocketLogger.swift */,
|
||||
74171E5D1C10CD240062D398 /* SocketPacket.swift */,
|
||||
74171E5E1C10CD240062D398 /* SocketParsable.swift */,
|
||||
74171E5F1C10CD240062D398 /* SocketStringReader.swift */,
|
||||
74171E601C10CD240062D398 /* SocketTypes.swift */,
|
||||
74171E611C10CD240062D398 /* SwiftRegex.swift */,
|
||||
74171E621C10CD240062D398 /* WebSocket.swift */,
|
||||
);
|
||||
name = Source;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
CEBA569E1CDA0C0C00BA0389 /* utils */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */,
|
||||
CEBA56991CDA0B8200BA0389 /* String.swift */,
|
||||
);
|
||||
name = utils;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXHeadersBuildPhase section */
|
||||
@@ -513,7 +527,7 @@
|
||||
572EF20E1B51F12F00EEBB58 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 0710;
|
||||
LastSwiftUpdateCheck = 0730;
|
||||
LastUpgradeCheck = 0720;
|
||||
TargetAttributes = {
|
||||
572EF2181B51F16C00EEBB58 = {
|
||||
@@ -604,10 +618,12 @@
|
||||
files = (
|
||||
740CA1221C496EF700CB98F4 /* SocketEngineWebsocket.swift in Sources */,
|
||||
74171EA51C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
|
||||
CEBA569A1CDA0B8200BA0389 /* String.swift in Sources */,
|
||||
74171E751C10CD240062D398 /* SocketEngine.swift in Sources */,
|
||||
74171E691C10CD240062D398 /* SocketAckManager.swift in Sources */,
|
||||
7420CB791C49629E00956AA4 /* SocketEnginePollable.swift in Sources */,
|
||||
74ABF7771C3991C10078C657 /* SocketClientSpec.swift in Sources */,
|
||||
CEBA56961CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */,
|
||||
74ABF7771C3991C10078C657 /* SocketIOClientSpec.swift in Sources */,
|
||||
74171E871C10CD240062D398 /* SocketEngineSpec.swift in Sources */,
|
||||
74171E631C10CD240062D398 /* SocketAckEmitter.swift in Sources */,
|
||||
74171EBD1C10CD240062D398 /* SocketStringReader.swift in Sources */,
|
||||
@@ -615,7 +631,6 @@
|
||||
74171EAB1C10CD240062D398 /* SocketLogger.swift in Sources */,
|
||||
74171E991C10CD240062D398 /* SocketIOClient.swift in Sources */,
|
||||
74171E8D1C10CD240062D398 /* SocketEventHandler.swift in Sources */,
|
||||
74171EC91C10CD240062D398 /* SwiftRegex.swift in Sources */,
|
||||
74171E7B1C10CD240062D398 /* SocketEngineClient.swift in Sources */,
|
||||
74171ECF1C10CD240062D398 /* WebSocket.swift in Sources */,
|
||||
74171EB11C10CD240062D398 /* SocketPacket.swift in Sources */,
|
||||
@@ -640,7 +655,6 @@
|
||||
74171E8E1C10CD240062D398 /* SocketEventHandler.swift in Sources */,
|
||||
74171E7C1C10CD240062D398 /* SocketEngineClient.swift in Sources */,
|
||||
74171E821C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
|
||||
74171ECA1C10CD240062D398 /* SwiftRegex.swift in Sources */,
|
||||
74171EB21C10CD240062D398 /* SocketPacket.swift in Sources */,
|
||||
741F39EE1BD025D80026C9CC /* SocketEngineTest.swift in Sources */,
|
||||
74171EBE1C10CD240062D398 /* SocketStringReader.swift in Sources */,
|
||||
@@ -660,10 +674,12 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
740CA1211C496EF200CB98F4 /* SocketEngineWebsocket.swift in Sources */,
|
||||
7471CCEA1C39926300364B59 /* SocketClientSpec.swift in Sources */,
|
||||
7471CCEA1C39926300364B59 /* SocketIOClientSpec.swift in Sources */,
|
||||
CEBA569B1CDA0B8200BA0389 /* String.swift in Sources */,
|
||||
74171EA71C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
|
||||
74171E771C10CD240062D398 /* SocketEngine.swift in Sources */,
|
||||
7420CB7A1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */,
|
||||
CEBA56971CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */,
|
||||
74171E6B1C10CD240062D398 /* SocketAckManager.swift in Sources */,
|
||||
74171E891C10CD240062D398 /* SocketEngineSpec.swift in Sources */,
|
||||
74171E651C10CD240062D398 /* SocketAckEmitter.swift in Sources */,
|
||||
@@ -672,7 +688,6 @@
|
||||
74171EAD1C10CD240062D398 /* SocketLogger.swift in Sources */,
|
||||
74171E9B1C10CD240062D398 /* SocketIOClient.swift in Sources */,
|
||||
74171E8F1C10CD240062D398 /* SocketEventHandler.swift in Sources */,
|
||||
74171ECB1C10CD240062D398 /* SwiftRegex.swift in Sources */,
|
||||
74171E7D1C10CD240062D398 /* SocketEngineClient.swift in Sources */,
|
||||
74171ED11C10CD240062D398 /* WebSocket.swift in Sources */,
|
||||
74171EB31C10CD240062D398 /* SocketPacket.swift in Sources */,
|
||||
@@ -687,6 +702,7 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
742D150C1CA5794B00BD987D /* SocketObjectiveCTest.m in Sources */,
|
||||
74321DCB1C2D939A00CF6F43 /* SocketAckManagerTest.swift in Sources */,
|
||||
74321DCC1C2D939A00CF6F43 /* SocketParserTest.swift in Sources */,
|
||||
7472C6601BCAC46E003CA70D /* SocketSideEffectTest.swift in Sources */,
|
||||
@@ -702,10 +718,12 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
740CA1201C496EEB00CB98F4 /* SocketEngineWebsocket.swift in Sources */,
|
||||
7471CCEB1C39926C00364B59 /* SocketClientSpec.swift in Sources */,
|
||||
7471CCEB1C39926C00364B59 /* SocketIOClientSpec.swift in Sources */,
|
||||
CEBA569C1CDA0B8200BA0389 /* String.swift in Sources */,
|
||||
74171EA91C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
|
||||
74171E791C10CD240062D398 /* SocketEngine.swift in Sources */,
|
||||
7420CB7B1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */,
|
||||
CEBA56981CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */,
|
||||
74171E6D1C10CD240062D398 /* SocketAckManager.swift in Sources */,
|
||||
74171E8B1C10CD240062D398 /* SocketEngineSpec.swift in Sources */,
|
||||
74171E671C10CD240062D398 /* SocketAckEmitter.swift in Sources */,
|
||||
@@ -714,7 +732,6 @@
|
||||
74171EAF1C10CD240062D398 /* SocketLogger.swift in Sources */,
|
||||
74171E9D1C10CD240062D398 /* SocketIOClient.swift in Sources */,
|
||||
74171E911C10CD240062D398 /* SocketEventHandler.swift in Sources */,
|
||||
74171ECD1C10CD240062D398 /* SwiftRegex.swift in Sources */,
|
||||
74171E7F1C10CD240062D398 /* SocketEngineClient.swift in Sources */,
|
||||
74171ED31C10CD240062D398 /* WebSocket.swift in Sources */,
|
||||
74171EB51C10CD240062D398 /* SocketPacket.swift in Sources */,
|
||||
@@ -739,7 +756,6 @@
|
||||
74171E921C10CD240062D398 /* SocketEventHandler.swift in Sources */,
|
||||
74171E801C10CD240062D398 /* SocketEngineClient.swift in Sources */,
|
||||
74171E861C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
|
||||
74171ECE1C10CD240062D398 /* SwiftRegex.swift in Sources */,
|
||||
74171EB61C10CD240062D398 /* SocketPacket.swift in Sources */,
|
||||
57634A2A1BD9B46D00E19CD7 /* SocketEngineTest.swift in Sources */,
|
||||
74171EC21C10CD240062D398 /* SocketStringReader.swift in Sources */,
|
||||
@@ -1169,6 +1185,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -1269,7 +1286,7 @@
|
||||
SDKROOT = appletvos;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TARGETED_DEVICE_FAMILY = 3;
|
||||
TVOS_DEPLOYMENT_TARGET = 9.0;
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
VERSION_INFO_PREFIX = "";
|
||||
@@ -1320,7 +1337,7 @@
|
||||
PRODUCT_NAME = SocketIO;
|
||||
SDKROOT = appletvos;
|
||||
SKIP_INSTALL = YES;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TARGETED_DEVICE_FAMILY = 3;
|
||||
TVOS_DEPLOYMENT_TARGET = 9.0;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
|
||||
@@ -145,4 +145,20 @@ class SocketBasicPacketTest: XCTestCase {
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data2, data])
|
||||
}
|
||||
|
||||
func testBinaryStringPlaceholderInMessage() {
|
||||
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) {
|
||||
var packet = packet
|
||||
XCTAssertEqual(packet.event, "test")
|
||||
packet.addData(data)
|
||||
packet.addData(data2)
|
||||
XCTAssertEqual(packet.args[0] as? String, "~~0")
|
||||
} else {
|
||||
XCTFail()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,4 +86,20 @@ class SocketEngineTest: XCTestCase {
|
||||
engine.parsePollingMessage("41:42[\"stringTest\",\"lïne one\\nlīne \\rtwo\"]")
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testEncodeURLProperly() {
|
||||
engine.connectParams = [
|
||||
"created": "2016-05-04T18:31:15+0200"
|
||||
]
|
||||
|
||||
XCTAssertEqual(engine.urlPolling.query, "transport=polling&b64=1&created=2016-05-04T18%3A31%3A15%2B0200")
|
||||
XCTAssertEqual(engine.urlWebSocket.query, "transport=websocket&created=2016-05-04T18%3A31%3A15%2B0200")
|
||||
|
||||
engine.connectParams = [
|
||||
"forbidden": "!*'();:@&=+$,/?%#[]\" {}"
|
||||
]
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//
|
||||
// SocketObjectiveCTest.m
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/25/16.
|
||||
//
|
||||
// Merely tests whether the Objective-C api breaks
|
||||
//
|
||||
|
||||
#import <XCTest/XCTest.h>
|
||||
@import SocketIOClientSwift;
|
||||
|
||||
@interface SocketObjectiveCTest : XCTestCase
|
||||
|
||||
@property SocketIOClient* socket;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SocketObjectiveCTest
|
||||
|
||||
- (void)setUp {
|
||||
[super setUp];
|
||||
NSURL* url = [[NSURL alloc] initWithString:@"http://localhost"];
|
||||
self.socket = [[SocketIOClient alloc] initWithSocketURL:url options:nil];
|
||||
}
|
||||
|
||||
- (void)testOnSyntax {
|
||||
[self.socket on:@"someCallback" callback:^(NSArray* data, SocketAckEmitter* ack) {
|
||||
[ack with:@[@1]];
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)testEmitSyntax {
|
||||
[self.socket emit:@"testEmit" withItems:@[@YES]];
|
||||
}
|
||||
|
||||
- (void)testEmitWithAckSyntax {
|
||||
[self.socket emitWithAck:@"testAckEmit" withItems:@[@YES]](0, ^(NSArray* data) {
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
- (void)testOffSyntax {
|
||||
[self.socket off:@"test"];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -18,13 +18,15 @@ class SocketParserTest: XCTestCase {
|
||||
"25[\"test\"]": ("/", ["test"], [], 5),
|
||||
"2[\"test\",\"~~0\"]": ("/", ["test", "~~0"], [], -1),
|
||||
"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", "~~0"], [], -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], ["test": "bob"], 25, "polo", "~~0"], [], 19),
|
||||
"61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]":
|
||||
("/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)]
|
||||
|
||||
func testDisconnect() {
|
||||
@@ -87,6 +89,11 @@ class SocketParserTest: XCTestCase {
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testErrorTypeDictionary() {
|
||||
let message = "4{\"test\":2}"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testErrorTypeInt() {
|
||||
let message = "41"
|
||||
validateParseResult(message)
|
||||
@@ -117,8 +124,8 @@ class SocketParserTest: XCTestCase {
|
||||
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).isEqualToArray(validValues.1))
|
||||
XCTAssertTrue((packet.binary as NSArray).isEqualToArray(validValues.2))
|
||||
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()
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
//
|
||||
// NSCharacterSet.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Yannick Loriot on 5/4/16.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
extension NSCharacterSet {
|
||||
class var allowedURLCharacterSet: NSCharacterSet {
|
||||
return NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
public final class SocketAckEmitter: NSObject {
|
||||
public final class SocketAckEmitter : NSObject {
|
||||
let socket: SocketIOClient
|
||||
let ackNum: Int
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
private struct SocketAck: Hashable, Equatable {
|
||||
private struct SocketAck : Hashable, Equatable {
|
||||
let ack: Int
|
||||
var callback: AckCallback!
|
||||
var hashValue: Int {
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
public final class SocketAnyEvent: NSObject {
|
||||
public final class SocketAnyEvent : NSObject {
|
||||
public let event: String
|
||||
public let items: NSArray?
|
||||
override public var description: String {
|
||||
|
||||
+41
-72
@@ -24,7 +24,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWebsocket {
|
||||
public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWebsocket {
|
||||
public let emitQueue = dispatch_queue_create("com.socketio.engineEmitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
public let handleQueue = dispatch_queue_create("com.socketio.engineHandleQueue", DISPATCH_QUEUE_SERIAL)
|
||||
public let parseQueue = dispatch_queue_create("com.socketio.engineParseQueue", DISPATCH_QUEUE_SERIAL)
|
||||
@@ -34,6 +34,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
(urlPolling, urlWebSocket) = createURLs()
|
||||
}
|
||||
}
|
||||
|
||||
public var postWait = [String]()
|
||||
public var waitingForPoll = false
|
||||
public var waitingForPost = false
|
||||
@@ -47,7 +48,6 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
public private(set) var forcePolling = false
|
||||
public private(set) var forceWebsockets = false
|
||||
public private(set) var invalidated = false
|
||||
public private(set) var pingTimer: NSTimer?
|
||||
public private(set) var polling = true
|
||||
public private(set) var probing = false
|
||||
public private(set) var session: NSURLSession?
|
||||
@@ -62,9 +62,6 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
|
||||
private weak var sessionDelegate: NSURLSessionDelegate?
|
||||
|
||||
private typealias Probe = (msg: String, type: SocketEnginePacketType, data: [NSData])
|
||||
private typealias ProbeWaitQueue = [Probe]
|
||||
|
||||
private let logType = "SocketEngine"
|
||||
private let url: NSURL
|
||||
|
||||
@@ -74,6 +71,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25))
|
||||
}
|
||||
}
|
||||
|
||||
private var pongsMissed = 0
|
||||
private var pongsMissedMax = 0
|
||||
private var probeWait = ProbeWaitQueue()
|
||||
@@ -123,18 +121,6 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? [])
|
||||
}
|
||||
|
||||
@available(*, deprecated=5.3, message="Please use the NSURL based init")
|
||||
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, message="Please use the NSURL based init")
|
||||
public convenience init(client: SocketEngineClient, urlString: String, options: NSDictionary?) {
|
||||
guard let url = NSURL(string: urlString) else { fatalError("Incorrect url") }
|
||||
self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? [])
|
||||
}
|
||||
|
||||
deinit {
|
||||
DefaultSocketLogger.Logger.log("Engine is being released", type: logType)
|
||||
closed = true
|
||||
@@ -146,23 +132,16 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
allowLossyConversion: false) else { return }
|
||||
|
||||
do {
|
||||
if let dict = try NSJSONSerialization.JSONObjectWithData(stringData,
|
||||
options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
|
||||
guard let code = dict["code"] as? Int else { return }
|
||||
guard let error = dict["message"] as? String else { return }
|
||||
|
||||
switch code {
|
||||
case 0: // Unknown transport
|
||||
didError(error)
|
||||
case 1: // Unknown sid.
|
||||
didError(error)
|
||||
case 2: // Bad handshake request
|
||||
didError(error)
|
||||
case 3: // Bad request
|
||||
didError(error)
|
||||
default:
|
||||
didError(error)
|
||||
}
|
||||
if let dict = try NSJSONSerialization.JSONObjectWithData(stringData, options: .MutableContainers) as? NSDictionary {
|
||||
guard let error = dict["message"] as? String else { return }
|
||||
|
||||
/*
|
||||
0: Unknown transport
|
||||
1: Unknown sid
|
||||
2: Bad handshake request
|
||||
3: Bad request
|
||||
*/
|
||||
didError(error)
|
||||
}
|
||||
} catch {
|
||||
didError("Got unknown error from server \(msg)")
|
||||
@@ -184,16 +163,12 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
public func close(reason: String) {
|
||||
disconnect(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)
|
||||
close("reconnect")
|
||||
disconnect("reconnect")
|
||||
}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Starting engine", type: logType)
|
||||
@@ -221,7 +196,9 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
}
|
||||
}
|
||||
|
||||
doLongPoll(reqPolling)
|
||||
dispatch_async(emitQueue) {
|
||||
self.doLongPoll(reqPolling)
|
||||
}
|
||||
}
|
||||
|
||||
private func createURLs() -> (NSURL, NSURL) {
|
||||
@@ -235,8 +212,6 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
|
||||
urlWebSocket.path = socketPath
|
||||
urlPolling.path = socketPath
|
||||
urlWebSocket.query = "transport=websocket"
|
||||
urlPolling.query = "transport=polling&b64=1"
|
||||
|
||||
if secure {
|
||||
urlPolling.scheme = "https"
|
||||
@@ -248,12 +223,15 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
|
||||
if connectParams != nil {
|
||||
for (key, value) in connectParams! {
|
||||
queryString += "&\(key)=\(value)"
|
||||
let keyEsc = key.urlEncode()!
|
||||
let valueEsc = "\(value)".urlEncode()!
|
||||
|
||||
queryString += "&\(keyEsc)=\(valueEsc)"
|
||||
}
|
||||
}
|
||||
|
||||
urlWebSocket.query = urlWebSocket.query! + queryString
|
||||
urlPolling.query = urlPolling.query! + queryString
|
||||
urlWebSocket.percentEncodedQuery = "transport=websocket" + queryString
|
||||
urlPolling.percentEncodedQuery = "transport=polling&b64=1" + queryString
|
||||
|
||||
return (urlPolling.URL!, urlWebSocket.URL!)
|
||||
}
|
||||
@@ -285,7 +263,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
public func didError(error: String) {
|
||||
DefaultSocketLogger.Logger.error(error, type: logType)
|
||||
client?.engineDidError(error)
|
||||
close(error)
|
||||
disconnect(error)
|
||||
}
|
||||
|
||||
public func disconnect(reason: String) {
|
||||
@@ -295,7 +273,6 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
invalidated = true
|
||||
connected = false
|
||||
|
||||
pingTimer?.invalidate()
|
||||
ws?.disconnect()
|
||||
stopPolling()
|
||||
client?.engineDidClose(reason)
|
||||
@@ -304,7 +281,8 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
|
||||
|
||||
if closed {
|
||||
return postSendClose(nil, nil, nil)
|
||||
client?.engineDidClose(reason)
|
||||
return
|
||||
}
|
||||
|
||||
if websocket {
|
||||
@@ -401,18 +379,16 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
createWebsocketAndConnect()
|
||||
}
|
||||
|
||||
|
||||
startPingTimer()
|
||||
sendPing()
|
||||
|
||||
if !forceWebsockets {
|
||||
doPoll()
|
||||
}
|
||||
|
||||
client?.engineDidOpen?("Connect")
|
||||
client?.engineDidOpen("Connect")
|
||||
}
|
||||
} catch {
|
||||
didError("Error parsing open packet")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -424,11 +400,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
upgradeTransport()
|
||||
}
|
||||
}
|
||||
|
||||
public func open() {
|
||||
connect()
|
||||
}
|
||||
|
||||
|
||||
public func parseEngineData(data: NSData) {
|
||||
DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data)
|
||||
client?.parseEngineBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
|
||||
@@ -487,30 +459,28 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
websocket = false
|
||||
}
|
||||
|
||||
@objc private func sendPing() {
|
||||
private func sendPing() {
|
||||
if !connected {
|
||||
return
|
||||
}
|
||||
|
||||
//Server is not responding
|
||||
if pongsMissed > pongsMissedMax {
|
||||
pingTimer?.invalidate()
|
||||
client?.engineDidClose("Ping timeout")
|
||||
return
|
||||
}
|
||||
|
||||
pongsMissed += 1
|
||||
write("", withType: .Ping, withData: [])
|
||||
}
|
||||
|
||||
private func startPingTimer() {
|
||||
|
||||
if let pingInterval = pingInterval {
|
||||
pingTimer?.invalidate()
|
||||
pingTimer = nil
|
||||
pongsMissed += 1
|
||||
write("", withType: .Ping, withData: [])
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self,
|
||||
selector: #selector(SocketEngine.sendPing), userInfo: nil, repeats: true)
|
||||
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 {
|
||||
@@ -562,7 +532,6 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
|
||||
}
|
||||
|
||||
if websocket {
|
||||
pingTimer?.invalidate()
|
||||
connected = false
|
||||
websocket = false
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ import Foundation
|
||||
@objc public protocol SocketEngineClient {
|
||||
func engineDidError(reason: String)
|
||||
func engineDidClose(reason: String)
|
||||
optional func engineDidOpen(reason: String)
|
||||
func engineDidOpen(reason: String)
|
||||
func parseEngineMessage(msg: String)
|
||||
func parseEngineBinaryData(data: NSData)
|
||||
}
|
||||
@@ -25,6 +25,6 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
@objc public enum SocketEnginePacketType: Int {
|
||||
@objc public enum SocketEnginePacketType : Int {
|
||||
case Open, Close, Ping, Pong, Message, Upgrade, Noop
|
||||
}
|
||||
@@ -25,7 +25,7 @@
|
||||
import Foundation
|
||||
|
||||
/// Protocol that is used to implement socket.io polling support
|
||||
public protocol SocketEnginePollable: SocketEngineSpec {
|
||||
public protocol SocketEnginePollable : SocketEngineSpec {
|
||||
var invalidated: Bool { get }
|
||||
/// Holds strings waiting to be sent over polling.
|
||||
/// You shouldn't need to mess with this.
|
||||
@@ -181,9 +181,7 @@ extension SocketEnginePollable {
|
||||
}
|
||||
|
||||
func parsePollingMessage(str: String) {
|
||||
guard str.characters.count != 1 else {
|
||||
return
|
||||
}
|
||||
guard str.characters.count != 1 else { return }
|
||||
|
||||
var reader = SocketStringReader(message: str)
|
||||
|
||||
@@ -210,7 +208,7 @@ extension SocketEnginePollable {
|
||||
let fixedMessage: String
|
||||
|
||||
if doubleEncodeUTF8 {
|
||||
fixedMessage = doubleEncodeUTF8(message)
|
||||
fixedMessage = doubleEncodeUTF8(message)
|
||||
} else {
|
||||
fixedMessage = message
|
||||
}
|
||||
|
||||
@@ -37,7 +37,6 @@ import Foundation
|
||||
var forcePolling: Bool { get }
|
||||
var forceWebsockets: Bool { get }
|
||||
var parseQueue: dispatch_queue_t! { get }
|
||||
var pingTimer: NSTimer? { get }
|
||||
var polling: Bool { get }
|
||||
var probing: Bool { get }
|
||||
var emitQueue: dispatch_queue_t! { get }
|
||||
@@ -47,16 +46,15 @@ import Foundation
|
||||
var urlPolling: NSURL { get }
|
||||
var urlWebSocket: NSURL { get }
|
||||
var websocket: Bool { get }
|
||||
var ws: WebSocket? { get }
|
||||
|
||||
init(client: SocketEngineClient, url: NSURL, options: NSDictionary?)
|
||||
|
||||
@available(*, deprecated=5.5, message="Please use disconnect") func close(reason: String)
|
||||
func connect()
|
||||
func didError(error: String)
|
||||
func disconnect(reason: String)
|
||||
func doFastUpgrade()
|
||||
func flushWaitingForPostToWebSocket()
|
||||
@available(*, deprecated=5.5, message="Please use connect") func open()
|
||||
func parseEngineData(data: NSData)
|
||||
func parseEngineMessage(message: String, fromPolling: Bool)
|
||||
func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData])
|
||||
@@ -65,14 +63,14 @@ import Foundation
|
||||
extension SocketEngineSpec {
|
||||
var urlPollingWithSid: NSURL {
|
||||
let com = NSURLComponents(URL: urlPolling, resolvingAgainstBaseURL: false)!
|
||||
com.query = com.query! + "&sid=\(sid)"
|
||||
com.percentEncodedQuery = com.percentEncodedQuery! + "&sid=\(sid.urlEncode()!)"
|
||||
|
||||
return com.URL!
|
||||
}
|
||||
|
||||
var urlWebSocketWithSid: NSURL {
|
||||
let com = NSURLComponents(URL: urlWebSocket, resolvingAgainstBaseURL: false)!
|
||||
com.query = com.query! + (sid == "" ? "" : "&sid=\(sid)")
|
||||
com.percentEncodedQuery = com.percentEncodedQuery! + (sid == "" ? "" : "&sid=\(sid.urlEncode()!)")
|
||||
|
||||
return com.URL!
|
||||
}
|
||||
|
||||
@@ -26,9 +26,7 @@
|
||||
import Foundation
|
||||
|
||||
/// Protocol that is used to implement socket.io WebSocket support
|
||||
public protocol SocketEngineWebsocket: SocketEngineSpec, WebSocketDelegate {
|
||||
var ws: WebSocket? { get }
|
||||
|
||||
public protocol SocketEngineWebsocket : SocketEngineSpec, WebSocketDelegate {
|
||||
func sendWebSocketMessage(str: String, withType type: SocketEnginePacketType, withData datas: [NSData])
|
||||
}
|
||||
|
||||
|
||||
+38
-68
@@ -24,7 +24,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable {
|
||||
public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable {
|
||||
public let socketURL: NSURL
|
||||
|
||||
public private(set) var engine: SocketEngineSpec?
|
||||
@@ -46,7 +46,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
public var reconnects = true
|
||||
public var reconnectWait = 10
|
||||
public var sid: String? {
|
||||
return engine?.sid
|
||||
return nsp + "#" + (engine?.sid ?? "")
|
||||
}
|
||||
|
||||
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
@@ -108,18 +108,6 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
self.init(socketURL: socketURL, options: options?.toSocketOptionsSet() ?? [])
|
||||
}
|
||||
|
||||
@available(*, deprecated=5.3, message="Please use the NSURL based init")
|
||||
public convenience init(socketURLString: String, options: Set<SocketIOClientOption> = []) {
|
||||
guard let url = NSURL(string: socketURLString) else { fatalError("Incorrect url") }
|
||||
self.init(socketURL: url, options: options)
|
||||
}
|
||||
|
||||
@available(*, deprecated=5.3, message="Please use the NSURL based init")
|
||||
public convenience init(socketURLString: String, options: NSDictionary?) {
|
||||
guard let url = NSURL(string: socketURLString) else { fatalError("Incorrect url") }
|
||||
self.init(socketURL: url, options: options?.toSocketOptionsSet() ?? [])
|
||||
}
|
||||
|
||||
deinit {
|
||||
DefaultSocketLogger.Logger.log("Client is being released", type: logType)
|
||||
engine?.disconnect("Client Deinit")
|
||||
@@ -133,11 +121,6 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
return engine!
|
||||
}
|
||||
|
||||
@available(*, deprecated=5.3, message="Please use disconnect()")
|
||||
public func close() {
|
||||
disconnect()
|
||||
}
|
||||
|
||||
/// Connect to the server.
|
||||
public func connect() {
|
||||
connect(timeoutAfter: 0, withTimeoutHandler: nil)
|
||||
@@ -148,8 +131,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
|
||||
|
||||
guard status != .Connected else {
|
||||
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket",
|
||||
type: logType)
|
||||
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket", type: logType)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -166,8 +148,8 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
|
||||
|
||||
dispatch_after(time, handleQueue) {[weak self] in
|
||||
if let this = self where this.status != .Connected && this.status != .Closed {
|
||||
this.status = .Closed
|
||||
if let this = self where this.status != .Connected && this.status != .Disconnected {
|
||||
this.status = .Disconnected
|
||||
this.engine?.disconnect("Connect timeout")
|
||||
|
||||
handler?()
|
||||
@@ -181,10 +163,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
return {[weak self, ack = currentAck] timeout, callback in
|
||||
if let this = self {
|
||||
this.ackHandlers.addAck(ack, callback: callback)
|
||||
|
||||
dispatch_async(this.emitQueue) {
|
||||
this._emit(items, ack: ack)
|
||||
}
|
||||
this._emit(items, ack: ack)
|
||||
|
||||
if timeout != 0 {
|
||||
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
|
||||
@@ -207,12 +186,11 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
}
|
||||
|
||||
func didDisconnect(reason: String) {
|
||||
guard status != .Closed else { return }
|
||||
guard status != .Disconnected else { return }
|
||||
|
||||
DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason)
|
||||
|
||||
status = .Closed
|
||||
reconnects = false
|
||||
status = .Disconnected
|
||||
|
||||
// Make sure the engine is actually dead.
|
||||
engine?.disconnect(reason)
|
||||
@@ -222,9 +200,10 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
/// Disconnects the socket. Only reconnect the same socket if you know what you're doing.
|
||||
/// Will turn off automatic reconnects.
|
||||
public func disconnect() {
|
||||
assert(status != .NotConnected, "Tried closing a NotConnected client")
|
||||
|
||||
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
|
||||
|
||||
reconnects = false
|
||||
didDisconnect("Disconnect")
|
||||
}
|
||||
|
||||
@@ -240,38 +219,34 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(emitQueue) {[emitData = [event] + items] in
|
||||
self._emit(emitData)
|
||||
}
|
||||
_emit([event] + items)
|
||||
}
|
||||
|
||||
/**
|
||||
Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
|
||||
an ack.
|
||||
*/
|
||||
/// Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
|
||||
/// an ack.
|
||||
public func emitWithAck(event: String, _ items: AnyObject...) -> OnAckCallback {
|
||||
return emitWithAck(event, withItems: items)
|
||||
}
|
||||
|
||||
/**
|
||||
Same as emitWithAck, but for Objective-C
|
||||
*/
|
||||
/// Same as emitWithAck, but for Objective-C
|
||||
public func emitWithAck(event: String, withItems items: [AnyObject]) -> OnAckCallback {
|
||||
return createOnAck([event] + items)
|
||||
}
|
||||
|
||||
private func _emit(data: [AnyObject], ack: Int? = nil) {
|
||||
guard status == .Connected else {
|
||||
handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
|
||||
return
|
||||
dispatch_async(emitQueue) {
|
||||
guard self.status == .Connected else {
|
||||
self.handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
|
||||
return
|
||||
}
|
||||
|
||||
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: self.nsp, ack: false)
|
||||
let str = packet.packetString
|
||||
|
||||
DefaultSocketLogger.Logger.log("Emitting: %@", type: self.logType, args: str)
|
||||
|
||||
self.engine?.send(str, withData: packet.binary)
|
||||
}
|
||||
|
||||
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
|
||||
let str = packet.packetString
|
||||
|
||||
DefaultSocketLogger.Logger.log("Emitting: %@", type: logType, args: str)
|
||||
|
||||
engine?.send(str, withData: packet.binary)
|
||||
}
|
||||
|
||||
// If the server wants to know that the client received data
|
||||
@@ -291,11 +266,11 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
public func engineDidClose(reason: String) {
|
||||
waitingPackets.removeAll()
|
||||
|
||||
if status != .Closed {
|
||||
if status != .Disconnected {
|
||||
status = .NotConnected
|
||||
}
|
||||
|
||||
if status == .Closed || !reconnects {
|
||||
if status == .Disconnected || !reconnects {
|
||||
didDisconnect(reason)
|
||||
} else if !reconnecting {
|
||||
reconnecting = true
|
||||
@@ -309,10 +284,14 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
|
||||
handleEvent("error", data: [reason], isInternalMessage: true)
|
||||
}
|
||||
|
||||
public func engineDidOpen(reason: String) {
|
||||
DefaultSocketLogger.Logger.log(reason, type: "SocketEngineClient")
|
||||
}
|
||||
|
||||
// Called when the socket gets an ack for something it sent
|
||||
func handleAck(ack: Int, data: [AnyObject]) {
|
||||
guard status == .Connected else {return}
|
||||
guard status == .Connected else { return }
|
||||
|
||||
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
|
||||
|
||||
@@ -321,9 +300,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
|
||||
/// Causes an event to be handled. Only use if you know what you're doing.
|
||||
public func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool, withAck ack: Int = -1) {
|
||||
guard status == .Connected || isInternalMessage else {
|
||||
return
|
||||
}
|
||||
guard status == .Connected || isInternalMessage else { return }
|
||||
|
||||
DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data ?? "")
|
||||
|
||||
@@ -358,14 +335,14 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
public func off(event: String) {
|
||||
DefaultSocketLogger.Logger.log("Removing handler for event: %@", type: logType, args: event)
|
||||
|
||||
handlers = handlers.filter { $0.event != 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 }
|
||||
handlers = handlers.filter({ $0.id != id })
|
||||
}
|
||||
|
||||
/// Adds a handler for an event.
|
||||
@@ -402,11 +379,6 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
anyHandler = handler
|
||||
}
|
||||
|
||||
@available(*, deprecated=5.3, message="Please use one of the connect methods)")
|
||||
public func open() {
|
||||
connect()
|
||||
}
|
||||
|
||||
public func parseEngineMessage(msg: String) {
|
||||
DefaultSocketLogger.Logger.log("Should parse message: %@", type: "SocketIOClient", args: msg)
|
||||
|
||||
@@ -443,15 +415,13 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func _tryReconnect() {
|
||||
private func _tryReconnect() {
|
||||
if !reconnecting {
|
||||
return
|
||||
}
|
||||
|
||||
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
|
||||
didDisconnect("Reconnect Failed")
|
||||
|
||||
return
|
||||
return didDisconnect("Reconnect Failed")
|
||||
}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType)
|
||||
|
||||
@@ -24,11 +24,11 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol ClientOption: CustomStringConvertible, Hashable {
|
||||
protocol ClientOption : CustomStringConvertible, Hashable {
|
||||
func getSocketIOOptionValue() -> AnyObject
|
||||
}
|
||||
|
||||
public enum SocketIOClientOption: ClientOption {
|
||||
public enum SocketIOClientOption : ClientOption {
|
||||
case ConnectParams([String: AnyObject])
|
||||
case Cookies([NSHTTPCookie])
|
||||
case DoubleEncodeUTF8(Bool)
|
||||
@@ -152,7 +152,7 @@ public func ==(lhs: SocketIOClientOption, rhs: SocketIOClientOption) -> Bool {
|
||||
return lhs.description == rhs.description
|
||||
}
|
||||
|
||||
extension Set where Element: ClientOption {
|
||||
extension Set where Element : ClientOption {
|
||||
mutating func insertIgnore(element: Element) {
|
||||
if !contains(element) {
|
||||
insert(element)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//
|
||||
// SocketClientSpec.swift
|
||||
// SocketIOClientSpec.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 1/3/16.
|
||||
@@ -22,7 +22,7 @@
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
protocol SocketClientSpec: class {
|
||||
protocol SocketIOClientSpec : class {
|
||||
var nsp: String { get set }
|
||||
var waitingPackets: [SocketPacket] { get set }
|
||||
|
||||
@@ -34,7 +34,7 @@ protocol SocketClientSpec: class {
|
||||
func joinNamespace(namespace: String)
|
||||
}
|
||||
|
||||
extension SocketClientSpec {
|
||||
extension SocketIOClientSpec {
|
||||
func didError(reason: String) {
|
||||
DefaultSocketLogger.Logger.error("%@", type: "SocketIOClient", args: reason)
|
||||
|
||||
@@ -24,19 +24,9 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
@objc public enum SocketIOClientStatus: Int, CustomStringConvertible {
|
||||
case NotConnected, Closed, Connecting, Connected
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case NotConnected:
|
||||
return "Not Connected"
|
||||
case Closed:
|
||||
return "Closed"
|
||||
case Connecting:
|
||||
return "Connecting"
|
||||
case Connected:
|
||||
return "Connected"
|
||||
}
|
||||
}
|
||||
}
|
||||
/// **NotConnected**: initial state
|
||||
///
|
||||
/// **Disconnected**: connected before
|
||||
@objc public enum SocketIOClientStatus : Int {
|
||||
case NotConnected, Disconnected, Connecting, Connected
|
||||
}
|
||||
@@ -24,9 +24,9 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
public protocol SocketLogger: class {
|
||||
public protocol SocketLogger : class {
|
||||
/// Whether to log or not
|
||||
var log: Bool {get set}
|
||||
var log: Bool { get set }
|
||||
|
||||
/// Normal log messages
|
||||
func log(message: String, type: String, args: AnyObject...)
|
||||
@@ -54,7 +54,7 @@ public extension SocketLogger {
|
||||
}
|
||||
}
|
||||
|
||||
class DefaultSocketLogger: SocketLogger {
|
||||
class DefaultSocketLogger : SocketLogger {
|
||||
static var Logger: SocketLogger = DefaultSocketLogger()
|
||||
|
||||
var log = false
|
||||
|
||||
+13
-11
@@ -61,7 +61,7 @@ struct SocketPacket {
|
||||
return createPacketString()
|
||||
}
|
||||
|
||||
init(type: SocketPacket.PacketType, data: [AnyObject] = [AnyObject](), id: Int = -1,
|
||||
init(type: PacketType, data: [AnyObject] = [AnyObject](), id: Int = -1,
|
||||
nsp: String, placeholders: Int = 0, binary: [NSData] = [NSData]()) {
|
||||
self.data = data
|
||||
self.id = id
|
||||
@@ -97,7 +97,7 @@ struct SocketPacket {
|
||||
let jsonSend = try NSJSONSerialization.dataWithJSONObject(data,
|
||||
options: NSJSONWritingOptions(rawValue: 0))
|
||||
guard let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding) else {
|
||||
return "[]"
|
||||
return message + "[]"
|
||||
}
|
||||
|
||||
restOfMessage = jsonString
|
||||
@@ -187,19 +187,21 @@ struct SocketPacket {
|
||||
data = data.map(_fillInPlaceholders)
|
||||
}
|
||||
|
||||
// Helper method that looks for placeholder strings
|
||||
// Helper method that looks for placeholders
|
||||
// If object is a collection it will recurse
|
||||
// Returns the object if it is not a placeholder string or the corresponding
|
||||
// Returns the object if it is not a placeholder or the corresponding
|
||||
// binary data
|
||||
private func _fillInPlaceholders(object: AnyObject) -> AnyObject {
|
||||
switch object {
|
||||
case let string as String where string["~~(\\d)"].groups() != nil:
|
||||
return binary[Int(string["~~(\\d)"].groups()![1])!]
|
||||
case let dict as NSDictionary:
|
||||
return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in
|
||||
cur[keyValue.0 as! NSCopying] = _fillInPlaceholders(keyValue.1)
|
||||
return cur
|
||||
})
|
||||
if dict["_placeholder"] as? Bool ?? false {
|
||||
return binary[dict["num"] as! Int]
|
||||
} else {
|
||||
return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in
|
||||
cur[keyValue.0 as! NSCopying] = _fillInPlaceholders(keyValue.1)
|
||||
return cur
|
||||
})
|
||||
}
|
||||
case let arr as [AnyObject]:
|
||||
return arr.map(_fillInPlaceholders)
|
||||
default:
|
||||
@@ -227,7 +229,7 @@ extension 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, placeholders: -1, binary: binary)
|
||||
id: id, nsp: nsp, binary: binary)
|
||||
|
||||
return packet
|
||||
}
|
||||
|
||||
+12
-16
@@ -22,7 +22,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol SocketParsable: SocketClientSpec {
|
||||
protocol SocketParsable : SocketIOClientSpec {
|
||||
func parseBinaryData(data: NSData)
|
||||
func parseSocketMessage(message: String)
|
||||
}
|
||||
@@ -35,8 +35,6 @@ extension SocketParsable {
|
||||
private func handleConnect(p: SocketPacket) {
|
||||
if p.nsp == "/" && nsp != "/" {
|
||||
joinNamespace(nsp)
|
||||
} else if p.nsp != "/" && nsp == "/" {
|
||||
didConnect()
|
||||
} else {
|
||||
didConnect()
|
||||
}
|
||||
@@ -45,8 +43,7 @@ extension SocketParsable {
|
||||
private func handlePacket(pack: SocketPacket) {
|
||||
switch pack.type {
|
||||
case .Event where isCorrectNamespace(pack.nsp):
|
||||
handleEvent(pack.event, data: pack.args,
|
||||
isInternalMessage: false, withAck: pack.id)
|
||||
handleEvent(pack.event, data: pack.args, isInternalMessage: false, withAck: pack.id)
|
||||
case .Ack where isCorrectNamespace(pack.nsp):
|
||||
handleAck(pack.id, data: pack.data)
|
||||
case .BinaryEvent where isCorrectNamespace(pack.nsp):
|
||||
@@ -76,7 +73,7 @@ extension SocketParsable {
|
||||
return .Right(SocketPacket(type: type, nsp: "/"))
|
||||
}
|
||||
|
||||
var namespace: String?
|
||||
var namespace = "/"
|
||||
var placeholders = -1
|
||||
|
||||
if type == .BinaryEvent || type == .BinaryAck {
|
||||
@@ -92,8 +89,7 @@ extension SocketParsable {
|
||||
}
|
||||
|
||||
if !parser.hasNext {
|
||||
return .Right(SocketPacket(type: type, id: -1,
|
||||
nsp: namespace ?? "/", placeholders: placeholders))
|
||||
return .Right(SocketPacket(type: type, nsp: namespace, placeholders: placeholders))
|
||||
}
|
||||
|
||||
var idString = ""
|
||||
@@ -112,30 +108,30 @@ extension SocketParsable {
|
||||
}
|
||||
|
||||
let d = message[parser.currentIndex.advancedBy(1)..<message.endIndex]
|
||||
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] <~ "\"~~$2\""
|
||||
|
||||
switch parseData(noPlaceholders) {
|
||||
switch parseData(d) {
|
||||
case let .Left(err):
|
||||
// If first you don't succeed, try again
|
||||
if case let .Right(data) = parseData("\([noPlaceholders as AnyObject])") {
|
||||
// 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))
|
||||
nsp: namespace, placeholders: placeholders))
|
||||
} else {
|
||||
return .Left(err)
|
||||
}
|
||||
case let .Right(data):
|
||||
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
|
||||
nsp: namespace ?? "/", placeholders: placeholders))
|
||||
nsp: namespace, placeholders: placeholders))
|
||||
}
|
||||
}
|
||||
|
||||
// Parses data for events
|
||||
private func parseData(data: String) -> Either<String, [AnyObject]> {
|
||||
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
||||
|
||||
do {
|
||||
if let arr = try NSJSONSerialization.JSONObjectWithData(stringData!,
|
||||
options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] {
|
||||
return .Right(arr)
|
||||
options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] {
|
||||
return .Right(arr)
|
||||
} else {
|
||||
return .Left("Expected data array")
|
||||
}
|
||||
|
||||
@@ -28,6 +28,9 @@ public typealias AckCallback = ([AnyObject]) -> Void
|
||||
public typealias NormalCallback = ([AnyObject], SocketAckEmitter) -> Void
|
||||
public typealias OnAckCallback = (timeoutAfter: UInt64, callback: AckCallback) -> Void
|
||||
|
||||
typealias Probe = (msg: String, type: SocketEnginePacketType, data: [NSData])
|
||||
typealias ProbeWaitQueue = [Probe]
|
||||
|
||||
enum Either<E, V> {
|
||||
case Left(E)
|
||||
case Right(V)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
//
|
||||
// String.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Yannick Loriot on 5/4/16.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
extension String {
|
||||
func urlEncode() -> String? {
|
||||
return stringByAddingPercentEncodingWithAllowedCharacters(.allowedURLCharacterSet)
|
||||
}
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
//
|
||||
// SwiftRegex.swift
|
||||
// SwiftRegex
|
||||
//
|
||||
// Created by John Holdsworth on 26/06/2014.
|
||||
// Copyright (c) 2014 John Holdsworth.
|
||||
//
|
||||
// $Id: //depot/SwiftRegex/SwiftRegex.swift#37 $
|
||||
//
|
||||
// This code is in the public domain from:
|
||||
// https://github.com/johnno1962/SwiftRegex
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
infix operator <~ { associativity none precedence 130 }
|
||||
|
||||
private let lock = dispatch_semaphore_create(1)
|
||||
private var swiftRegexCache = [String: NSRegularExpression]()
|
||||
|
||||
internal final class SwiftRegex: NSObject, BooleanType {
|
||||
var target: String
|
||||
var regex: NSRegularExpression
|
||||
|
||||
init(target:String, pattern:String, options:NSRegularExpressionOptions?) {
|
||||
self.target = target
|
||||
|
||||
if dispatch_semaphore_wait(lock, dispatch_time(DISPATCH_TIME_NOW, Int64(10 * NSEC_PER_MSEC))) != 0 {
|
||||
do {
|
||||
let regex = try NSRegularExpression(pattern: pattern, options:
|
||||
NSRegularExpressionOptions.DotMatchesLineSeparators)
|
||||
self.regex = regex
|
||||
} catch let error as NSError {
|
||||
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
|
||||
self.regex = NSRegularExpression()
|
||||
}
|
||||
|
||||
super.init()
|
||||
return
|
||||
}
|
||||
|
||||
if let regex = swiftRegexCache[pattern] {
|
||||
self.regex = regex
|
||||
} else {
|
||||
do {
|
||||
let regex = try NSRegularExpression(pattern: pattern, options:
|
||||
NSRegularExpressionOptions.DotMatchesLineSeparators)
|
||||
swiftRegexCache[pattern] = regex
|
||||
self.regex = regex
|
||||
} catch let error as NSError {
|
||||
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
|
||||
self.regex = NSRegularExpression()
|
||||
}
|
||||
}
|
||||
dispatch_semaphore_signal(lock)
|
||||
super.init()
|
||||
}
|
||||
|
||||
private static func failure(message: String) {
|
||||
fatalError("SwiftRegex: \(message)")
|
||||
}
|
||||
|
||||
private var targetRange: NSRange {
|
||||
return NSRange(location: 0,length: target.utf16.count)
|
||||
}
|
||||
|
||||
private func substring(range: NSRange) -> String? {
|
||||
if range.location != NSNotFound {
|
||||
return (target as NSString).substringWithRange(range)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func doesMatch(options: NSMatchingOptions!) -> Bool {
|
||||
return range(options).location != NSNotFound
|
||||
}
|
||||
|
||||
func range(options: NSMatchingOptions) -> NSRange {
|
||||
return regex.rangeOfFirstMatchInString(target as String, options: [], range: targetRange)
|
||||
}
|
||||
|
||||
func match(options: NSMatchingOptions) -> String? {
|
||||
return substring(range(options))
|
||||
}
|
||||
|
||||
func groups() -> [String]? {
|
||||
return groupsForMatch(regex.firstMatchInString(target as String, options:
|
||||
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange))
|
||||
}
|
||||
|
||||
private func groupsForMatch(match: NSTextCheckingResult?) -> [String]? {
|
||||
guard let match = match else {
|
||||
return nil
|
||||
}
|
||||
var groups = [String]()
|
||||
for groupno in 0...regex.numberOfCaptureGroups {
|
||||
if let group = substring(match.rangeAtIndex(groupno)) {
|
||||
groups += [group]
|
||||
} else {
|
||||
groups += ["_"] // avoids bridging problems
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
subscript(groupno: Int) -> String? {
|
||||
get {
|
||||
return groups()?[groupno]
|
||||
}
|
||||
|
||||
set(newValue) {
|
||||
if newValue == nil {
|
||||
return
|
||||
}
|
||||
|
||||
for match in Array(matchResults().reverse()) {
|
||||
let replacement = regex.replacementStringForResult(match,
|
||||
inString: target as String, offset: 0, template: newValue!)
|
||||
let mut = NSMutableString(string: target)
|
||||
mut.replaceCharactersInRange(match.rangeAtIndex(groupno), withString: replacement)
|
||||
|
||||
target = mut as String
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func matchResults() -> [NSTextCheckingResult] {
|
||||
let matches = regex.matchesInString(target as String, options:
|
||||
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange)
|
||||
as [NSTextCheckingResult]
|
||||
|
||||
return matches
|
||||
}
|
||||
|
||||
func ranges() -> [NSRange] {
|
||||
return matchResults().map { $0.range }
|
||||
}
|
||||
|
||||
func matches() -> [String] {
|
||||
return matchResults().map( { self.substring($0.range)!})
|
||||
}
|
||||
|
||||
func allGroups() -> [[String]?] {
|
||||
return matchResults().map { self.groupsForMatch($0) }
|
||||
}
|
||||
|
||||
func dictionary(options: NSMatchingOptions!) -> Dictionary<String,String> {
|
||||
var out = Dictionary<String,String>()
|
||||
for match in matchResults() {
|
||||
out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))!
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String),
|
||||
options:NSMatchingOptions) -> String {
|
||||
let out = NSMutableString()
|
||||
var pos = 0
|
||||
|
||||
regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {match, flags, stop in
|
||||
let matchRange = match!.range
|
||||
out.appendString( self.substring(NSRange(location:pos, length:matchRange.location-pos))!)
|
||||
out.appendString( substitution(match!, stop) )
|
||||
pos = matchRange.location + matchRange.length
|
||||
}
|
||||
|
||||
out.appendString(substring(NSRange(location:pos, length:targetRange.length-pos))!)
|
||||
|
||||
return out as String
|
||||
}
|
||||
|
||||
var boolValue: Bool {
|
||||
return doesMatch(nil)
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex {
|
||||
return SwiftRegex(target: self, pattern: pattern, options: options)
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
subscript(pattern: String) -> SwiftRegex {
|
||||
return SwiftRegex(target: self, pattern: pattern, options: nil)
|
||||
}
|
||||
}
|
||||
|
||||
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: [])
|
||||
}
|
||||
+125
-96
@@ -112,6 +112,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
public var security: SSLSecurity?
|
||||
public var enabledSSLCipherSuites: [SSLCipherSuite]?
|
||||
public var origin: String?
|
||||
public var timeout = 5
|
||||
public var isConnected :Bool {
|
||||
return connected
|
||||
}
|
||||
@@ -180,30 +181,42 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
///write a string to the websocket. This sends it as a text frame.
|
||||
public func writeString(str: String) {
|
||||
/**
|
||||
Write a string to the websocket. This sends it as a text frame.
|
||||
|
||||
If you supply a non-nil completion block, I will perform it when the write completes.
|
||||
- parameter str: The string to write.
|
||||
- parameter completion: The (optional) completion handler.
|
||||
*/
|
||||
public func writeString(str: String, completion: (() -> ())? = nil) {
|
||||
guard isConnected else { return }
|
||||
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame)
|
||||
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame, writeCompletion: completion)
|
||||
}
|
||||
|
||||
///write binary data to the websocket. This sends it as a binary frame.
|
||||
public func writeData(data: NSData) {
|
||||
/**
|
||||
Write binary data to the websocket. This sends it as a binary frame.
|
||||
|
||||
If you supply a non-nil completion block, I will perform it when the write completes.
|
||||
- parameter data: The data to write.
|
||||
- parameter completion: The (optional) completion handler.
|
||||
*/
|
||||
public func writeData(data: NSData, completion: (() -> ())? = nil) {
|
||||
guard isConnected else { return }
|
||||
dequeueWrite(data, code: .BinaryFrame)
|
||||
dequeueWrite(data, code: .BinaryFrame, writeCompletion: completion)
|
||||
}
|
||||
|
||||
//write a ping to the websocket. This sends it as a control frame.
|
||||
//yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
|
||||
public func writePing(data: NSData) {
|
||||
public func writePing(data: NSData, completion: (() -> ())? = nil) {
|
||||
guard isConnected else { return }
|
||||
dequeueWrite(data, code: .Ping)
|
||||
dequeueWrite(data, code: .Ping, writeCompletion: completion)
|
||||
}
|
||||
|
||||
//private method that starts the connection
|
||||
private func createHTTPRequest() {
|
||||
|
||||
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
|
||||
url, kCFHTTPVersion1_1).takeRetainedValue()
|
||||
url, kCFHTTPVersion1_1).takeRetainedValue()
|
||||
|
||||
var port = url.port
|
||||
if port == nil {
|
||||
@@ -283,18 +296,18 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if let cipherSuites = self.enabledSSLCipherSuites {
|
||||
if let sslContextIn = CFReadStreamCopyProperty(inputStream, kCFStreamPropertySSLContext) as! SSLContextRef?,
|
||||
sslContextOut = CFWriteStreamCopyProperty(outputStream, kCFStreamPropertySSLContext) as! SSLContextRef? {
|
||||
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
|
||||
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
|
||||
if resIn != errSecSuccess {
|
||||
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
|
||||
disconnectStream(error)
|
||||
return
|
||||
}
|
||||
if resOut != errSecSuccess {
|
||||
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
|
||||
disconnectStream(error)
|
||||
return
|
||||
}
|
||||
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
|
||||
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
|
||||
if resIn != errSecSuccess {
|
||||
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
|
||||
disconnectStream(error)
|
||||
return
|
||||
}
|
||||
if resOut != errSecSuccess {
|
||||
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
|
||||
disconnectStream(error)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue)
|
||||
@@ -307,12 +320,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
self.mutex.unlock()
|
||||
|
||||
let bytes = UnsafePointer<UInt8>(data.bytes)
|
||||
var timeout = 5000000 //wait 5 seconds before giving up
|
||||
var out = timeout * 1000000 //wait 5 seconds before giving up
|
||||
writeQueue.addOperationWithBlock { [weak self] in
|
||||
while !outStream.hasSpaceAvailable {
|
||||
usleep(100) //wait until the socket is ready
|
||||
timeout -= 100
|
||||
if timeout < 0 {
|
||||
out -= 100
|
||||
if out < 0 {
|
||||
self?.cleanupStream()
|
||||
self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2))
|
||||
return
|
||||
@@ -393,25 +406,24 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
///dequeue the incoming input so it is processed in order
|
||||
private func dequeueInput() {
|
||||
guard !inputQueue.isEmpty else { return }
|
||||
|
||||
let data = inputQueue[0]
|
||||
var work = data
|
||||
if let fragBuffer = fragBuffer {
|
||||
let combine = NSMutableData(data: fragBuffer)
|
||||
combine.appendData(data)
|
||||
work = combine
|
||||
self.fragBuffer = nil
|
||||
while !inputQueue.isEmpty {
|
||||
let data = inputQueue[0]
|
||||
var work = data
|
||||
if let fragBuffer = fragBuffer {
|
||||
let combine = NSMutableData(data: fragBuffer)
|
||||
combine.appendData(data)
|
||||
work = combine
|
||||
self.fragBuffer = nil
|
||||
}
|
||||
let buffer = UnsafePointer<UInt8>(work.bytes)
|
||||
let length = work.length
|
||||
if !connected {
|
||||
processTCPHandshake(buffer, bufferLen: length)
|
||||
} else {
|
||||
processRawMessagesInBuffer(buffer, bufferLen: length)
|
||||
}
|
||||
inputQueue = inputQueue.filter{$0 != data}
|
||||
}
|
||||
let buffer = UnsafePointer<UInt8>(work.bytes)
|
||||
let length = work.length
|
||||
if !connected {
|
||||
processTCPHandshake(buffer, bufferLen: length)
|
||||
} else {
|
||||
processRawMessage(buffer, bufferLen: length)
|
||||
}
|
||||
inputQueue = inputQueue.filter{$0 != data}
|
||||
dequeueInput()
|
||||
}
|
||||
|
||||
//handle checking the inital connection status
|
||||
@@ -428,7 +440,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
case -1:
|
||||
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
||||
break //do nothing, we are going to collect more data
|
||||
break //do nothing, we are going to collect more data
|
||||
default:
|
||||
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
|
||||
}
|
||||
@@ -457,7 +469,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
totalSize += 1 //skip the last \n
|
||||
let restSize = bufferLen - totalSize
|
||||
if restSize > 0 {
|
||||
processRawMessage((buffer+totalSize),bufferLen: restSize)
|
||||
processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize)
|
||||
}
|
||||
return 0 //success
|
||||
}
|
||||
@@ -510,12 +522,15 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
///process the websocket data
|
||||
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
||||
/// Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process.
|
||||
@warn_unused_result
|
||||
private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> {
|
||||
let response = readStack.last
|
||||
let baseAddress = buffer.baseAddress
|
||||
let bufferLen = buffer.count
|
||||
if response != nil && bufferLen < 2 {
|
||||
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
||||
return
|
||||
fragBuffer = NSData(buffer: buffer)
|
||||
return emptyBuffer
|
||||
}
|
||||
if let response = response where response.bytesLeft > 0 {
|
||||
var len = response.bytesLeft
|
||||
@@ -525,45 +540,41 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
extra = 0
|
||||
}
|
||||
response.bytesLeft -= len
|
||||
response.buffer?.appendData(NSData(bytes: buffer, length: len))
|
||||
response.buffer?.appendData(NSData(bytes: baseAddress, length: len))
|
||||
processResponse(response)
|
||||
let offset = bufferLen - extra
|
||||
if extra > 0 {
|
||||
processExtra((buffer+offset), bufferLen: extra)
|
||||
}
|
||||
return
|
||||
return buffer.fromOffset(bufferLen - extra)
|
||||
} else {
|
||||
let isFin = (FinMask & buffer[0])
|
||||
let receivedOpcode = OpCode(rawValue: (OpCodeMask & buffer[0]))
|
||||
let isMasked = (MaskMask & buffer[1])
|
||||
let payloadLen = (PayloadLenMask & buffer[1])
|
||||
let isFin = (FinMask & baseAddress[0])
|
||||
let receivedOpcode = OpCode(rawValue: (OpCodeMask & baseAddress[0]))
|
||||
let isMasked = (MaskMask & baseAddress[1])
|
||||
let payloadLen = (PayloadLenMask & baseAddress[1])
|
||||
var offset = 2
|
||||
if (isMasked > 0 || (RSVMask & buffer[0]) > 0) && receivedOpcode != .Pong {
|
||||
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .Pong {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
return emptyBuffer
|
||||
}
|
||||
let isControlFrame = (receivedOpcode == .ConnectionClose || receivedOpcode == .Ping)
|
||||
if !isControlFrame && (receivedOpcode != .BinaryFrame && receivedOpcode != .ContinueFrame &&
|
||||
receivedOpcode != .TextFrame && receivedOpcode != .Pong) {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
|
||||
writeError(errCode)
|
||||
return emptyBuffer
|
||||
}
|
||||
if isControlFrame && isFin == 0 {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
return emptyBuffer
|
||||
}
|
||||
if receivedOpcode == .ConnectionClose {
|
||||
var code = CloseCode.Normal.rawValue
|
||||
if payloadLen == 1 {
|
||||
code = CloseCode.ProtocolError.rawValue
|
||||
} else if payloadLen > 1 {
|
||||
code = WebSocket.readUint16(buffer, offset: offset)
|
||||
code = WebSocket.readUint16(baseAddress, offset: offset)
|
||||
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
|
||||
code = CloseCode.ProtocolError.rawValue
|
||||
}
|
||||
@@ -572,7 +583,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if payloadLen > 2 {
|
||||
let len = Int(payloadLen-2)
|
||||
if len > 0 {
|
||||
let bytes = UnsafePointer<UInt8>((buffer+offset))
|
||||
let bytes = baseAddress + offset
|
||||
let str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
|
||||
if str == nil {
|
||||
code = CloseCode.ProtocolError.rawValue
|
||||
@@ -581,34 +592,34 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
doDisconnect(errorWithDetail("connection closed by server", code: code))
|
||||
writeError(code)
|
||||
return
|
||||
return emptyBuffer
|
||||
}
|
||||
if isControlFrame && payloadLen > 125 {
|
||||
writeError(CloseCode.ProtocolError.rawValue)
|
||||
return
|
||||
return emptyBuffer
|
||||
}
|
||||
var dataLength = UInt64(payloadLen)
|
||||
if dataLength == 127 {
|
||||
dataLength = WebSocket.readUint64(buffer, offset: offset)
|
||||
dataLength = WebSocket.readUint64(baseAddress, offset: offset)
|
||||
offset += sizeof(UInt64)
|
||||
} else if dataLength == 126 {
|
||||
dataLength = UInt64(WebSocket.readUint16(buffer, offset: offset))
|
||||
dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset))
|
||||
offset += sizeof(UInt16)
|
||||
}
|
||||
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
|
||||
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
||||
return
|
||||
fragBuffer = NSData(bytes: baseAddress, length: bufferLen)
|
||||
return emptyBuffer
|
||||
}
|
||||
var len = dataLength
|
||||
if dataLength > UInt64(bufferLen) {
|
||||
len = UInt64(bufferLen-offset)
|
||||
}
|
||||
var data: NSData!
|
||||
let data: NSData
|
||||
if len < 0 {
|
||||
len = 0
|
||||
data = NSData()
|
||||
} else {
|
||||
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
|
||||
data = NSData(bytes: baseAddress+offset, length: Int(len))
|
||||
}
|
||||
if receivedOpcode == .Pong {
|
||||
if canDispatch {
|
||||
@@ -618,12 +629,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
s.pongDelegate?.websocketDidReceivePong(s)
|
||||
}
|
||||
}
|
||||
let step = Int(offset+numericCast(len))
|
||||
let extra = bufferLen-step
|
||||
if extra > 0 {
|
||||
processRawMessage((buffer+step), bufferLen: extra)
|
||||
}
|
||||
return
|
||||
return buffer.fromOffset(offset + Int(len))
|
||||
}
|
||||
var response = readStack.last
|
||||
if isControlFrame {
|
||||
@@ -633,7 +639,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
return emptyBuffer
|
||||
}
|
||||
var isNew = false
|
||||
if response == nil {
|
||||
@@ -642,7 +648,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
doDisconnect(errorWithDetail("first frame can't be a continue frame",
|
||||
code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
return emptyBuffer
|
||||
}
|
||||
isNew = true
|
||||
response = WSResponse()
|
||||
@@ -657,7 +663,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame",
|
||||
code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
return emptyBuffer
|
||||
}
|
||||
response!.buffer!.appendData(data)
|
||||
}
|
||||
@@ -672,20 +678,18 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
|
||||
let step = Int(offset+numericCast(len))
|
||||
let extra = bufferLen-step
|
||||
if extra > 0 {
|
||||
processExtra((buffer+step), bufferLen: extra)
|
||||
}
|
||||
return buffer.fromOffset(step)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
///process the extra of a buffer
|
||||
private func processExtra(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
||||
if bufferLen < 2 {
|
||||
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
||||
} else {
|
||||
processRawMessage(buffer, bufferLen: bufferLen)
|
||||
/// Process all messages in the buffer if possible.
|
||||
private func processRawMessagesInBuffer(pointer: UnsafePointer<UInt8>, bufferLen: Int) {
|
||||
var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen)
|
||||
repeat {
|
||||
buffer = processOneRawMessage(inBuffer: buffer)
|
||||
} while buffer.count >= 2
|
||||
if buffer.count > 0 {
|
||||
fragBuffer = NSData(buffer: buffer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -739,7 +743,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
|
||||
}
|
||||
///used to write things to the stream
|
||||
private func dequeueWrite(data: NSData, code: OpCode) {
|
||||
private func dequeueWrite(data: NSData, code: OpCode, writeCompletion: (() -> ())? = nil) {
|
||||
writeQueue.addOperationWithBlock { [weak self] in
|
||||
//stream isn't ready, let's wait
|
||||
guard let s = self else { return }
|
||||
@@ -788,6 +792,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
total += len
|
||||
}
|
||||
if total >= offset {
|
||||
if let queue = self?.queue, callback = writeCompletion {
|
||||
dispatch_async(queue) {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -817,6 +827,25 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
|
||||
}
|
||||
|
||||
private extension NSData {
|
||||
|
||||
convenience init(buffer: UnsafeBufferPointer<UInt8>) {
|
||||
self.init(bytes: buffer.baseAddress, length: buffer.count)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private extension UnsafeBufferPointer {
|
||||
|
||||
func fromOffset(offset: Int) -> UnsafeBufferPointer<Element> {
|
||||
return UnsafeBufferPointer<Element>(start: baseAddress.advancedBy(offset), count: count - offset)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
|
||||
|
||||
|
||||
public class SSLCert {
|
||||
var certData: NSData?
|
||||
var key: SecKeyRef?
|
||||
|
||||
Reference in new issue
Block a user