Compare commits

...
53 Commits
Author SHA1 Message Date
Erik 16e0bf6319 bump version 2016-02-25 19:13:08 -05:00
Erik Little 11c0ac249b Merge pull request #317 from jtjacka/master
fix timeoutAfter handler always close connection
2016-02-25 19:11:33 -05:00
jtjacka 1e96d7982d fix timeoutAfter handler always close connection 2016-02-25 16:06:08 -08:00
Erik 2f4c942dcf use connect/disconnect for engine 2016-02-23 10:33:14 -05:00
Erik 70283acc1f add messages to deprecated methods 2016-02-17 14:27:48 -05:00
Erik e16914f7d6 remove unused param 2016-02-17 14:15:15 -05:00
Erik c795f9fb25 refactor socketpacket 2016-02-17 14:09:05 -05:00
Erik 12f9207d8a rename waitingData to waitingPackets 2016-02-16 17:03:00 -05:00
Erik 0bf27b8c49 bump version 2016-02-16 14:28:18 -05:00
Erik 6ac96f8d91 modify test 2016-02-16 14:27:18 -05:00
Erik f7397155b6 add test cases 2016-02-16 14:26:21 -05:00
Erik 70d59ea9d4 fix quotes in strings 2016-02-16 14:21:10 -05:00
Erik 7fe2dc2c70 bump version 2016-02-15 10:48:24 -05:00
Erik fe9ee602e7 add option for toggling double encoding utf8 2016-02-15 10:43:21 -05:00
Erik 6fa5ce9168 don't call connect timeout if status is closed 2016-02-14 20:16:01 -05:00
Erik 43b2d4646f bump websocket version 2016-02-12 08:45:44 -05:00
Erik 0f70079382 fix possible race condition 2016-02-11 09:36:36 -05:00
Erik 750ba138e1 bump version 2016-02-05 14:05:50 -05:00
Erik 3e8ca90e3a don't fatalerror 2016-02-05 13:09:26 -05:00
Erik 2a25027077 change to weak self 2016-02-04 15:59:39 -05:00
Erik 15dfba42a7 bump version 2016-02-04 10:15:50 -05:00
Erik 76ef3596f0 possible fix for socketio/socket.io-client-swift#279 2016-02-01 21:56:49 -05:00
Erik 8e208b1c66 bump websocket version again 2016-01-29 16:57:50 -05:00
Erik 8c9a93f79d bump version 2016-01-29 16:54:16 -05:00
Erik cf651b8a00 Don't add newlines to base64 encoded stuff. Fixes nuclearace/Socket.IO-Client-Swft#105 2016-01-29 16:53:19 -05:00
Erik b8307b6b27 refactor test 2016-01-29 13:08:41 -05:00
Erik fe3599d1fe add test for parsing double encoded utf8 2016-01-29 13:06:56 -05:00
Erik 8d22de967e bump websocket version 2016-01-28 09:09:29 -05:00
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
20 changed files with 461 additions and 363 deletions

No files matched your search

+18 -17
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.2.0 # Or latest version
github "socketio/socket.io-client-swift" ~> 5.5.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.2.0' # Or latest version
pod 'Socket.IO-Client-Swift', '~> 5.5.0' # Or latest version
```
Install pods:
@@ -127,7 +128,7 @@ CocoaSeeds
Add this line to your `Seedfile`:
```
github "socketio/socket.io-client-swift", "v5.2.0", :files => "Source/*.swift" # Or latest version
github "socketio/socket.io-client-swift", "v5.5.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
-------
@@ -146,24 +147,24 @@ All options are a case of SocketIOClientOption. To get the Objective-C Option, c
```swift
case ConnectParams([String: AnyObject]) // Dictionary whose contents will be passed with the connection.
case Reconnects(Bool) // Whether to reconnect on server lose. Default is `true`
case ReconnectAttempts(Int) // How many times to reconnect. Default is `-1` (infinite tries)
case ReconnectWait(Int) // Amount of time to wait between reconnects. Default is `10`
case Cookies([NSHTTPCookie]) // An array of NSHTTPCookies. Passed during the handshake. Default is nil.
case DoubleEncodeUTF8(Bool) // Whether or not to double encode utf8. If using the node based server this should be true. Default is true.
case ExtraHeaders([String: String]) // Adds custom headers to the initial request. Default is nil.
case ForcePolling(Bool) // `true` forces the client to use xhr-polling. Default is `false`
case ForceNew(Bool) // Will a create a new engine for each connect. Useful if you find a bug in the engine related to reconnects
case ForceWebsockets(Bool) // `true` forces the client to use WebSockets. Default is `false`
case Nsp(String) // The namespace to connect to. Must begin with /. Default is `/`
case Cookies([NSHTTPCookie]) // An array of NSHTTPCookies. Passed during the handshake. Default is nil.
case HandleQueue(dispatch_queue_t) // The dispatch queue that handlers are run on. Default is the main queue.
case Log(Bool) // If `true` socket will log debug messages. Default is false.
case Logger(SocketLogger) // Custom logger that conforms to SocketLogger. Will use the default logging otherwise.
case Nsp(String) // The namespace to connect to. Must begin with /. Default is `/`
case Path(String) // If the server uses a custom path. ex: `"/swift/"`. Default is `""`
case Reconnects(Bool) // Whether to reconnect on server lose. Default is `true`
case ReconnectAttempts(Int) // How many times to reconnect. Default is `-1` (infinite tries)
case ReconnectWait(Int) // Amount of time to wait between reconnects. Default is `10`
case SessionDelegate(NSURLSessionDelegate) // Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
case 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
case Secure(Bool) // If the connection should use TLS. Default is false.
case SelfSigned(Bool) // Sets WebSocket.selfSignedSSL (Don't do this, iOS will yell at you)
case VoipEnabled(Bool) // Only use this option if you're using the client with VoIP services. Changes the way the WebSocket is created. Default is false
```
Methods
-------
+2 -2
View File
@@ -1,7 +1,7 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.module_name = "SocketIOClientSwift"
s.version = "5.2.0"
s.version = "5.5.0"
s.summary = "Socket.IO-client for iOS and OS X"
s.description = <<-DESC
Socket.IO-client for iOS and OS X.
@@ -14,7 +14,7 @@ Pod::Spec.new do |s|
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.tvos.deployment_target = '9.0'
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v5.2.0' }
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v5.5.0' }
s.source_files = "Source/**/*.swift"
s.requires_arc = true
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
@@ -60,11 +60,6 @@
74171E8F1C10CD240062D398 /* SocketEventHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E571C10CD240062D398 /* SocketEventHandler.swift */; };
74171E911C10CD240062D398 /* SocketEventHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E571C10CD240062D398 /* SocketEventHandler.swift */; };
74171E921C10CD240062D398 /* SocketEventHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E571C10CD240062D398 /* SocketEventHandler.swift */; };
74171E931C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
74171E941C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
74171E951C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
74171E971C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
74171E981C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
74171E991C10CD240062D398 /* SocketIOClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E591C10CD240062D398 /* SocketIOClient.swift */; };
74171E9A1C10CD240062D398 /* SocketIOClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E591C10CD240062D398 /* SocketIOClient.swift */; };
74171E9B1C10CD240062D398 /* SocketIOClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E591C10CD240062D398 /* SocketIOClient.swift */; };
@@ -180,7 +175,6 @@
74171E551C10CD240062D398 /* SocketEnginePacketType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketEnginePacketType.swift; path = Source/SocketEnginePacketType.swift; sourceTree = "<group>"; };
74171E561C10CD240062D398 /* SocketEngineSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketEngineSpec.swift; path = Source/SocketEngineSpec.swift; sourceTree = "<group>"; };
74171E571C10CD240062D398 /* SocketEventHandler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketEventHandler.swift; path = Source/SocketEventHandler.swift; sourceTree = "<group>"; };
74171E581C10CD240062D398 /* SocketFixUTF8.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketFixUTF8.swift; path = Source/SocketFixUTF8.swift; sourceTree = "<group>"; };
74171E591C10CD240062D398 /* SocketIOClient.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClient.swift; path = Source/SocketIOClient.swift; sourceTree = "<group>"; };
74171E5A1C10CD240062D398 /* SocketIOClientOption.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClientOption.swift; path = Source/SocketIOClientOption.swift; sourceTree = "<group>"; };
74171E5B1C10CD240062D398 /* SocketIOClientStatus.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClientStatus.swift; path = Source/SocketIOClientStatus.swift; sourceTree = "<group>"; };
@@ -361,7 +355,6 @@
74171E561C10CD240062D398 /* SocketEngineSpec.swift */,
740CA11F1C496EEB00CB98F4 /* SocketEngineWebsocket.swift */,
74171E571C10CD240062D398 /* SocketEventHandler.swift */,
74171E581C10CD240062D398 /* SocketFixUTF8.swift */,
74171E591C10CD240062D398 /* SocketIOClient.swift */,
74171E5A1C10CD240062D398 /* SocketIOClientOption.swift */,
74171E5B1C10CD240062D398 /* SocketIOClientStatus.swift */,
@@ -610,7 +603,6 @@
buildActionMask = 2147483647;
files = (
740CA1221C496EF700CB98F4 /* SocketEngineWebsocket.swift in Sources */,
74171E931C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
74171EA51C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
74171E751C10CD240062D398 /* SocketEngine.swift in Sources */,
74171E691C10CD240062D398 /* SocketAckManager.swift in Sources */,
@@ -647,7 +639,6 @@
74171EC41C10CD240062D398 /* SocketTypes.swift in Sources */,
74171E8E1C10CD240062D398 /* SocketEventHandler.swift in Sources */,
74171E7C1C10CD240062D398 /* SocketEngineClient.swift in Sources */,
74171E941C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
74171E821C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
74171ECA1C10CD240062D398 /* SwiftRegex.swift in Sources */,
74171EB21C10CD240062D398 /* SocketPacket.swift in Sources */,
@@ -670,7 +661,6 @@
files = (
740CA1211C496EF200CB98F4 /* SocketEngineWebsocket.swift in Sources */,
7471CCEA1C39926300364B59 /* SocketClientSpec.swift in Sources */,
74171E951C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
74171EA71C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
74171E771C10CD240062D398 /* SocketEngine.swift in Sources */,
7420CB7A1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */,
@@ -713,7 +703,6 @@
files = (
740CA1201C496EEB00CB98F4 /* SocketEngineWebsocket.swift in Sources */,
7471CCEB1C39926C00364B59 /* SocketClientSpec.swift in Sources */,
74171E971C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
74171EA91C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
74171E791C10CD240062D398 /* SocketEngine.swift in Sources */,
7420CB7B1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */,
@@ -749,7 +738,6 @@
74171EC81C10CD240062D398 /* SocketTypes.swift in Sources */,
74171E921C10CD240062D398 /* SocketEventHandler.swift in Sources */,
74171E801C10CD240062D398 /* SocketEngineClient.swift in Sources */,
74171E981C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
74171E861C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
74171ECE1C10CD240062D398 /* SwiftRegex.swift in Sources */,
74171EB61C10CD240062D398 /* SocketPacket.swift in Sources */,
@@ -37,6 +37,14 @@ class SocketBasicPacketTest: XCTestCase {
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testStringEmitWithQuotes() {
let expectedSendString = "2[\"test\",\"\\\"he\\\"llo world\\\"\"]"
let sendData = ["test", "\"he\"llo world\""]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testJSONEmit() {
let expectedSendString = "2[\"test\",{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
let sendData = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
+14 -2
View File
@@ -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()
}
@@ -74,4 +74,16 @@ class SocketEngineTest: XCTestCase {
engine.parseEngineMessage("afafafda", fromPolling: false)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testEngineDecodesUTF8Properly() {
let expectation = expectationWithDescription("Engine Decodes utf8")
client.on("stringTest") {data, ack in
XCTAssertEqual(data[0] as? String, "lïne one\nlīne \rtwo", "Failed string test")
expectation.fulfill()
}
engine.parsePollingMessage("41:42[\"stringTest\",\"lïne one\\nlīne \\rtwo\"]")
waitForExpectationsWithTimeout(3, handler: nil)
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ import XCTest
@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)> = [
+12 -1
View File
@@ -16,7 +16,7 @@ class SocketSideEffectTest: XCTestCase {
override func setUp() {
super.setUp()
socket = SocketIOClient(socketURL: "")
socket = SocketIOClient(socketURL: NSURL())
socket.setTestable()
}
@@ -70,6 +70,17 @@ class SocketSideEffectTest: XCTestCase {
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleStringEventWithQuotes() {
let expectation = expectationWithDescription("handled event")
socket.on("test") {data, ack in
XCTAssertEqual(data[0] as? String, "\"hello world\"")
expectation.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"\\\"hello world\\\"\"]")
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleOnceEvent() {
let expectation = expectationWithDescription("handled event")
socket.once("test") {data, ack in
+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)"
+1 -1
View File
@@ -24,7 +24,7 @@
protocol SocketClientSpec: class {
var nsp: String { get set }
var waitingData: [SocketPacket] { get set }
var waitingPackets: [SocketPacket] { get set }
func didConnect()
func didDisconnect(reason: String)
+134 -119
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
@@ -36,6 +41,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
public private(set) var closed = false
public private(set) var connected = false
public private(set) var cookies: [NSHTTPCookie]?
public private(set) var doubleEncodeUTF8 = true
public private(set) var extraHeaders: [String: String]?
public private(set) var fastUpgrade = false
public private(set) var forcePolling = false
@@ -46,9 +52,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 +65,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,25 +80,29 @@ 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 .Cookies(cookies):
self.cookies = cookies
case let .DoubleEncodeUTF8(encode):
doubleEncodeUTF8 = encode
case let .ExtraHeaders(headers):
extraHeaders = headers
case let .SessionDelegate(delegate):
sessionDelegate = delegate
case let .ForcePolling(force):
forcePolling = force
case let .ForceWebsockets(force):
forceWebsockets = force
case let .Cookies(cookies):
self.cookies = cookies
case let .Path(path):
socketPath = path
case let .ExtraHeaders(headers):
extraHeaders = headers
case let .VoipEnabled(enable):
voipEnabled = enable
case let .Secure(secure):
@@ -105,15 +113,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, 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 deinit", type: logType)
DefaultSocketLogger.Logger.log("Engine is being released", type: logType)
closed = true
stopPolling()
}
@@ -131,7 +154,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)
@@ -163,74 +186,80 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
public func close(reason: String) {
func postSendClose(data: NSData?, _ res: NSURLResponse?, _ err: NSError?) {
sid = ""
closed = true
invalidated = true
connected = false
pingTimer?.invalidate()
ws?.disconnect()
stopPolling()
client?.engineDidClose(reason)
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")
}
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
DefaultSocketLogger.Logger.log("Starting engine", type: logType)
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
if websocket {
sendWebSocketMessage("", withType: .Close, withData: [])
postSendClose(nil, nil, nil)
} else {
// We need to take special care when we're polling that we send it ASAP
postWait.append(String(SocketEnginePacketType.Close.rawValue))
let req = createRequestForPostWithPostWait()
doRequest(req, withCallback: postSendClose)
resetEngine()
if forceWebsockets {
polling = false
websocket = true
createWebsocketAndConnect()
return
}
let reqPolling = NSMutableURLRequest(URL: urlPolling)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doLongPoll(reqPolling)
}
private func createURLs(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() {
let wsUrl = urlWebSocket + (sid == "" ? "" : "&sid=\(sid)")
ws = WebSocket(url: NSURL(string: wsUrl)!)
ws = WebSocket(url: urlWebSocketWithSid)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
@@ -258,6 +287,35 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
client?.engineDidError(error)
close(error)
}
public func disconnect(reason: String) {
func postSendClose(data: NSData?, _ res: NSURLResponse?, _ err: NSError?) {
sid = ""
closed = true
invalidated = true
connected = false
pingTimer?.invalidate()
ws?.disconnect()
stopPolling()
client?.engineDidClose(reason)
}
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
if websocket {
sendWebSocketMessage("", withType: .Close, withData: [])
postSendClose(nil, nil, nil)
} else {
// We need to take special care when we're polling that we send it ASAP
// Also make sure we're on the emitQueue since we're touching postWait
dispatch_sync(emitQueue) {
self.postWait.append(String(SocketEnginePacketType.Close.rawValue))
let req = self.createRequestForPostWithPostWait()
self.doRequest(req, withCallback: postSendClose)
}
}
}
public func doFastUpgrade() {
if waitingForPoll {
@@ -363,43 +421,8 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
}
public func open(opts: [String: AnyObject]?) {
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()
return
}
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doLongPoll(reqPolling)
public func open() {
connect()
}
public func parseEngineData(data: NSData) {
@@ -421,7 +444,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
return
}
if fromPolling && type != .Noop {
if fromPolling && type != .Noop && doubleEncodeUTF8 {
fixedString = fixDoubleUTF8(message)
} else {
fixedString = message
@@ -443,6 +466,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
}
// Puts the engine back in its default state
private func resetEngine() {
closed = false
connected = false
@@ -458,15 +482,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
@@ -480,12 +495,11 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
write("", withType: .Ping, withData: [])
}
// Starts the ping timer
private func startPingTimer() {
if let pingInterval = pingInterval {
pingTimer?.invalidate()
pingTimer = nil
dispatch_async(dispatch_get_main_queue()) {
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self,
selector: Selector("sendPing"), userInfo: nil, repeats: true)
@@ -493,6 +507,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
}
// Moves from long-polling to websockets
private func upgradeTransport() {
if ws?.isConnected ?? false {
DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: logType)
@@ -503,9 +518,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
}
/**
Write a message, independent of transport.
*/
/// Write a message, independent of transport.
public func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData]) {
dispatch_async(emitQueue) {
guard self.connected else { return }
@@ -514,10 +527,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))
}
}
}
+24 -17
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")
@@ -206,21 +206,28 @@ extension SocketEnginePollable {
/// Send polling message.
/// Only call on emitQueue
public func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData]) {
DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue)
let fixedMessage = doubleEncodeUTF8(message)
let strMsg = "\(type.rawValue)\(fixedMessage)"
postWait.append(strMsg)
for data in datas {
if case let .Right(bin) = createBinaryDataForSend(data) {
postWait.append(bin)
}
}
if !waitingForPost {
flushWaitingForPost()
DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue)
let fixedMessage: String
if doubleEncodeUTF8 {
fixedMessage = doubleEncodeUTF8(message)
} else {
fixedMessage = message
}
let strMsg = "\(type.rawValue)\(fixedMessage)"
postWait.append(strMsg)
for data in datas {
if case let .Right(bin) = createBinaryDataForSend(data) {
postWait.append(bin)
}
}
if !waitingForPost {
flushWaitingForPost()
}
}
public func stopPolling() {
+48 -8
View File
@@ -29,6 +29,8 @@ import Foundation
weak var client: SocketEngineClient? { get set }
var closed: Bool { get }
var connected: Bool { get }
var connectParams: [String: AnyObject]? { get set }
var doubleEncodeUTF8: Bool { get }
var cookies: [NSHTTPCookie]? { get }
var extraHeaders: [String: String]? { get }
var fastUpgrade: Bool { get }
@@ -42,26 +44,41 @@ 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)
@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()
func open(opts: [String: AnyObject]?)
@available(*, deprecated=5.5, message="Please use connect") 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 {
if websocket {
var byteArray = [UInt8](count: 1, repeatedValue: 0x4)
let mutData = NSMutableData(bytes: &byteArray, length: 1)
@@ -69,9 +86,32 @@ extension SocketEngineSpec {
return .Left(mutData)
} else {
let str = "b4" + data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
let str = "b4" + data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
return .Right(str)
}
}
func doubleEncodeUTF8(string: String) -> String {
if let latin1 = string.dataUsingEncoding(NSUTF8StringEncoding),
utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding) {
return utf8 as String
} else {
return string
}
}
func fixDoubleUTF8(string: String) -> String {
if let utf8 = string.dataUsingEncoding(NSISOLatin1StringEncoding),
latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding) {
return latin1 as String
} else {
return string
}
}
/// Send an engine message (4)
func send(msg: String, withData datas: [NSData]) {
write(msg, withType: .Message, withData: datas)
}
}
-44
View File
@@ -1,44 +0,0 @@
//
// SocketFixUTF8.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/16/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// 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
func fixDoubleUTF8(string: String) -> String {
if let utf8 = string.dataUsingEncoding(NSISOLatin1StringEncoding),
latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding) {
return latin1 as String
} else {
return string
}
}
func doubleEncodeUTF8(string: String) -> String {
if let latin1 = string.dataUsingEncoding(NSUTF8StringEncoding),
utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding) {
return utf8 as String
} else {
return string
}
}
+49 -48
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>
@@ -54,24 +53,21 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
private(set) var handleQueue = dispatch_get_main_queue()
private(set) var reconnectAttempts = -1
var waitingData = [SocketPacket]()
var waitingPackets = [SocketPacket]()
/**
Type safe way to create a new SocketIOClient. opts can be omitted
*/
public init(socketURL: String, options: Set<SocketIOClientOption> = []) {
public init(socketURL: NSURL, options: Set<SocketIOClientOption> = []) {
self.options = options
if socketURL["https://"].matches().count != 0 {
self.socketURL = socketURL
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):
@@ -92,24 +88,35 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
continue
}
}
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, options: Set<SocketIOClientOption>)`
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() ?? [])
}
@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 deinit", type: logType)
engine?.close("Client Deinit")
DefaultSocketLogger.Logger.log("Client is being released", type: logType)
engine?.disconnect("Client Deinit")
}
private func addEngine() -> SocketEngineSpec {
@@ -125,7 +132,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
reconnectTimer = nil
}
@available(*, deprecated=6.0)
@available(*, deprecated=5.3, message="Please use disconnect()")
public func close() {
disconnect()
}
@@ -152,19 +159,19 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
status = .Connecting
if engine == nil || forceNew {
addEngine().open(connectParams)
addEngine().connect()
} else {
engine?.open(connectParams)
engine?.connect()
}
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 {
if let this = self where this.status != .Connected && this.status != .Closed {
this.status = .Closed
this.engine?.close("Connect timeout")
this.engine?.disconnect("Connect timeout")
handler?()
}
@@ -205,9 +212,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
func didDisconnect(reason: String) {
guard status != .Closed else {
return
}
guard status != .Closed else { return }
DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason)
@@ -215,7 +220,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
reconnects = false
// Make sure the engine is actually dead.
engine?.close(reason)
engine?.disconnect(reason)
handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
@@ -245,9 +250,9 @@ 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)
dispatch_async(emitQueue) {[emitData = [event] + items] in
self._emit(emitData)
}
}
@@ -271,10 +276,10 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
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)
@@ -295,14 +300,12 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
public func engineDidClose(reason: String) {
waitingData.removeAll()
waitingPackets.removeAll()
if status == .Closed || !reconnects {
didDisconnect(reason)
} else if status != .Reconnecting {
status = .Reconnecting
handleEvent("reconnect", data: [reason], isInternalMessage: true)
tryReconnect()
tryReconnectWithReason(reason)
}
}
@@ -404,7 +407,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
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)
}
@@ -421,10 +424,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
anyHandler = handler
}
/**
Same as connect
*/
@available(*, deprecated=6.0)
@available(*, deprecated=5.3, message="Please use one of the connect methods)")
public func open() {
connect()
}
@@ -447,7 +447,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
Tries to reconnect to the server.
*/
public func reconnect() {
tryReconnect()
tryReconnectWithReason("manual reconnect")
}
/**
@@ -458,9 +458,10 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
handlers.removeAll(keepCapacity: false)
}
private func tryReconnect() {
private func tryReconnectWithReason(reason: String) {
if reconnectTimer == nil {
DefaultSocketLogger.Logger.log("Starting reconnect", type: logType)
handleEvent("reconnect", data: [reason], isInternalMessage: true)
status = .Reconnecting
+26 -19
View File
@@ -31,6 +31,7 @@ protocol ClientOption: CustomStringConvertible, Hashable {
public enum SocketIOClientOption: ClientOption {
case ConnectParams([String: AnyObject])
case Cookies([NSHTTPCookie])
case DoubleEncodeUTF8(Bool)
case ExtraHeaders([String: String])
case ForceNew(Bool)
case ForcePolling(Bool)
@@ -56,6 +57,8 @@ public enum SocketIOClientOption: ClientOption {
description = "connectParams"
case .Cookies:
description = "cookies"
case .DoubleEncodeUTF8:
description = "doubleEncodeUTF8"
case .ExtraHeaders:
description = "extraHeaders"
case .ForceNew:
@@ -105,6 +108,8 @@ public enum SocketIOClientOption: ClientOption {
value = params
case let .Cookies(cookies):
value = cookies
case let .DoubleEncodeUTF8(encode):
value = encode
case let .ExtraHeaders(headers):
value = headers
case let .ForceNew(force):
@@ -156,44 +161,46 @@ extension Set where Element: ClientOption {
}
extension NSDictionary {
static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
private static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
switch (key, value) {
case let ("connectParams", params as [String: AnyObject]):
return .ConnectParams(params)
case let ("reconnects", reconnects as Bool):
return .Reconnects(reconnects)
case let ("reconnectAttempts", attempts as Int):
return .ReconnectAttempts(attempts)
case let ("reconnectWait", wait as Int):
return .ReconnectWait(wait)
case let ("cookies", cookies as [NSHTTPCookie]):
return .Cookies(cookies)
case let ("doubleEncodeUTF8", encode as Bool):
return .DoubleEncodeUTF8(encode)
case let ("extraHeaders", headers as [String: String]):
return .ExtraHeaders(headers)
case let ("forceNew", force as Bool):
return .ForceNew(force)
case let ("forcePolling", force as Bool):
return .ForcePolling(force)
case let ("forceWebsockets", force as Bool):
return .ForceWebsockets(force)
case let ("nsp", nsp as String):
return .Nsp(nsp)
case let ("cookies", cookies as [NSHTTPCookie]):
return .Cookies(cookies)
case let ("handleQueue", queue as dispatch_queue_t):
return .HandleQueue(queue)
case let ("log", log as Bool):
return .Log(log)
case let ("logger", logger as SocketLogger):
return .Logger(logger)
case let ("sessionDelegate", delegate as NSURLSessionDelegate):
return .SessionDelegate(delegate)
case let ("nsp", nsp as String):
return .Nsp(nsp)
case let ("path", path as String):
return .Path(path)
case let ("extraHeaders", headers as [String: String]):
return .ExtraHeaders(headers)
case let ("handleQueue", queue as dispatch_queue_t):
return .HandleQueue(queue)
case let ("voipEnabled", enable as Bool):
return .VoipEnabled(enable)
case let ("reconnects", reconnects as Bool):
return .Reconnects(reconnects)
case let ("reconnectAttempts", attempts as Int):
return .ReconnectAttempts(attempts)
case let ("reconnectWait", wait as Int):
return .ReconnectWait(wait)
case let ("secure", secure as Bool):
return .Secure(secure)
case let ("selfSigned", selfSigned as Bool):
return .SelfSigned(selfSigned)
case let ("sessionDelegate", delegate as NSURLSessionDelegate):
return .SessionDelegate(delegate)
case let ("voipEnabled", enable as Bool):
return .VoipEnabled(enable)
default:
return nil
}
+30 -40
View File
@@ -86,39 +86,29 @@ struct SocketPacket {
}
}
private func completeMessage(message: String, ack: Bool) -> String {
var restOfMessage = ""
private func completeMessage(message: String) -> String {
let restOfMessage: String
if data.count == 0 {
return message + "]"
return message + "[]"
}
for arg in data {
if arg is NSDictionary || arg is [AnyObject] {
do {
let jsonSend = try NSJSONSerialization.dataWithJSONObject(arg,
options: NSJSONWritingOptions(rawValue: 0))
let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding)
restOfMessage += jsonString! + ","
} catch {
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
type: SocketPacket.logType)
}
} else if let str = arg as? String {
restOfMessage += "\"" + ((str["\n"] <~ "\\\\n")["\r"] <~ "\\\\r") + "\","
} else if arg is NSNull {
restOfMessage += "null,"
} else {
restOfMessage += "\(arg),"
do {
let jsonSend = try NSJSONSerialization.dataWithJSONObject(data,
options: NSJSONWritingOptions(rawValue: 0))
guard let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding) else {
return "[]"
}
restOfMessage = jsonString
} catch {
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
type: SocketPacket.logType)
restOfMessage = "[]"
}
if restOfMessage != "" {
restOfMessage.removeAtIndex(restOfMessage.endIndex.predecessor())
}
return message + restOfMessage + "]"
return message + restOfMessage
}
private func createAck() -> String {
@@ -126,19 +116,19 @@ struct SocketPacket {
if type == .Ack {
if nsp == "/" {
message = "3\(id)["
message = "3\(id)"
} else {
message = "3\(nsp),\(id)["
message = "3\(nsp),\(id)"
}
} else {
if nsp == "/" {
message = "6\(binary.count)-\(id)["
message = "6\(binary.count)-\(id)"
} else {
message = "6\(binary.count)-\(nsp),\(id)["
message = "6\(binary.count)-\(nsp),\(id)"
}
}
return completeMessage(message, ack: true)
return completeMessage(message)
}
@@ -148,34 +138,34 @@ struct SocketPacket {
if type == .Event {
if nsp == "/" {
if id == -1 {
message = "2["
message = "2"
} else {
message = "2\(id)["
message = "2\(id)"
}
} else {
if id == -1 {
message = "2\(nsp),["
message = "2\(nsp),"
} else {
message = "2\(nsp),\(id)["
message = "2\(nsp),\(id)"
}
}
} else {
if nsp == "/" {
if id == -1 {
message = "5\(binary.count)-["
message = "5\(binary.count)-"
} else {
message = "5\(binary.count)-\(id)["
message = "5\(binary.count)-\(id)"
}
} else {
if id == -1 {
message = "5\(binary.count)-\(nsp),["
message = "5\(binary.count)-\(nsp),"
} else {
message = "5\(binary.count)-\(nsp),\(id)["
message = "5\(binary.count)-\(nsp),\(id)"
}
}
}
return completeMessage(message, ack: false)
return completeMessage(message)
}
private func createPacketString() -> String {
+6 -6
View File
@@ -50,15 +50,15 @@ extension SocketParsable {
case .Ack where isCorrectNamespace(pack.nsp):
handleAck(pack.id, data: pack.data)
case .BinaryEvent where isCorrectNamespace(pack.nsp):
waitingData.append(pack)
waitingPackets.append(pack)
case .BinaryAck where isCorrectNamespace(pack.nsp):
waitingData.append(pack)
waitingPackets.append(pack)
case .Connect:
handleConnect(pack)
case .Disconnect:
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)
}
@@ -160,17 +160,17 @@ extension SocketParsable {
}
func parseBinaryData(data: NSData) {
guard !waitingData.isEmpty else {
guard !waitingPackets.isEmpty else {
DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser")
return
}
// Should execute event?
guard waitingData[waitingData.count - 1].addData(data) else {
guard waitingPackets[waitingPackets.count - 1].addData(data) else {
return
}
let packet = waitingData.removeLast()
let packet = waitingPackets.removeLast()
if packet.type != .BinaryAck {
handleEvent(packet.event, data: packet.args ?? [],
+1 -1
View File
@@ -65,4 +65,4 @@ struct SocketStringReader {
mutating func readUntilEnd() -> String {
return read(currentIndex.distanceTo(message.endIndex))
}
}
}
+18 -1
View File
@@ -15,14 +15,30 @@ 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 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 {
@@ -36,6 +52,7 @@ internal final class SwiftRegex: NSObject, BooleanType {
self.regex = NSRegularExpression()
}
}
dispatch_semaphore_signal(lock)
super.init()
}
+67 -22
View File
@@ -127,6 +127,14 @@ public class WebSocket : NSObject, NSStreamDelegate {
private var fragBuffer: NSData?
private var certValidated = false
private var didDisconnect = false
private var readyToWrite = false
private let mutex = NSLock()
private var canDispatch: Bool {
mutex.lock()
let canWork = readyToWrite
mutex.unlock()
return canWork
}
//the shared processing queue used for all websocket
private static let sharedWorkQueue = dispatch_queue_create("com.vluxe.starscream.websocket", DISPATCH_QUEUE_SERIAL)
@@ -293,10 +301,25 @@ public class WebSocket : NSObject, NSStreamDelegate {
CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue)
inStream.open()
outStream.open()
self.mutex.lock()
self.readyToWrite = true
self.mutex.unlock()
let bytes = UnsafePointer<UInt8>(data.bytes)
writeQueue.addOperationWithBlock {
var timeout = 5000000 //wait 5 seconds before giving up
writeQueue.addOperationWithBlock { [weak self] in
guard let this = self else { return }
while !outStream.hasSpaceAvailable {
usleep(100) //wait until the socket is ready
timeout -= 100
if timeout < 0 {
this.cleanupStream()
this.doDisconnect(this.errorWithDetail("write wait timed out", code: 2))
return
} else if outStream.streamError != nil {
return //disconnectStream will be called.
}
}
outStream.write(bytes, maxLength: data.length)
}
@@ -330,6 +353,13 @@ public class WebSocket : NSObject, NSStreamDelegate {
//disconnect the stream object
private func disconnectStream(error: NSError?) {
writeQueue.waitUntilAllOperationsAreFinished()
cleanupStream()
doDisconnect(error)
}
private func cleanupStream() {
outputStream?.delegate = nil
inputStream?.delegate = nil
if let stream = inputStream {
CFReadStreamSetDispatchQueue(stream, nil)
stream.close()
@@ -339,8 +369,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
stream.close()
}
outputStream = nil
certValidated = false
doDisconnect(error)
inputStream = nil
}
///handles the incoming bytes and sending them to the proper processing method
@@ -388,12 +417,15 @@ public class WebSocket : NSObject, NSStreamDelegate {
switch code {
case 0:
connected = true
guard canDispatch else {return}
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onConnect?()
s.delegate?.websocketDidConnect(s)
}
case -1: break //do nothing, we are going to collect more data
case -1:
fragBuffer = NSData(bytes: buffer, length: bufferLen)
break //do nothing, we are going to collect more data
default:
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
}
@@ -405,7 +437,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
var totalSize = 0
for i in 0..<bufferLen {
if buffer[i] == CRLFBytes[k] {
k++
k += 1
if k == 3 {
totalSize = i + 1
break
@@ -576,12 +608,13 @@ public class WebSocket : NSObject, NSStreamDelegate {
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
}
if receivedOpcode == .Pong {
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onPong?()
s.pongDelegate?.websocketDidReceivePong(s)
if canDispatch {
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onPong?()
s.pongDelegate?.websocketDidReceivePong(s)
}
}
let step = Int(offset+numericCast(len))
let extra = bufferLen-step
if extra > 0 {
@@ -627,7 +660,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
if let response = response {
response.bytesLeft -= Int(len)
response.frameCount++
response.frameCount += 1
response.isFin = isFin > 0 ? true : false
if isNew {
readStack.append(response)
@@ -665,18 +698,21 @@ public class WebSocket : NSObject, NSStreamDelegate {
writeError(CloseCode.Encoding.rawValue)
return false
}
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onText?(str! as String)
s.delegate?.websocketDidReceiveMessage(s, text: str! as String)
if canDispatch {
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onText?(str! as String)
s.delegate?.websocketDidReceiveMessage(s, text: str! as String)
}
}
} else if response.code == .BinaryFrame {
let data = response.buffer! //local copy so it is perverse for writing
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onData?(data)
s.delegate?.websocketDidReceiveData(s, data: data)
if canDispatch {
let data = response.buffer! //local copy so it is perverse for writing
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onData?(data)
s.delegate?.websocketDidReceiveData(s, data: data)
}
}
}
readStack.removeLast()
@@ -761,6 +797,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
guard !didDisconnect else { return }
didDisconnect = true
connected = false
guard canDispatch else {return}
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onDisconnect?(error)
@@ -768,7 +805,15 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
}
deinit {
mutex.lock()
readyToWrite = false
mutex.unlock()
cleanupStream()
}
}
private class SSLCert {
var certData: NSData?
var key: SecKeyRef?
@@ -913,7 +958,7 @@ private class SSLSecurity {
for serverCert in serverCerts {
for cert in certs {
if cert == serverCert {
trustedCount++
trustedCount += 1
break
}
}