Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3faf183cb2 | ||
|
|
fafd8b5f22 | ||
|
|
373c1a3447 | ||
|
|
3d5cf24de4 | ||
|
|
1f8c8b8f61 | ||
|
|
9e94ed1cea | ||
|
|
01790af3c5 | ||
|
|
551ad7f6af | ||
|
|
b3fd4203d2 | ||
|
|
c462381587 | ||
|
|
99faafe723 | ||
|
|
efefecdbe3 | ||
|
|
fcb2b6bbf6 | ||
|
|
cce88ae3eb | ||
|
|
1616a58bd7 | ||
|
|
0fcb7903bb | ||
|
|
3db37023c7 | ||
|
|
e38bda7239 | ||
|
|
9a05f794f7 | ||
|
|
f943f41895 | ||
|
|
494f3fa199 | ||
|
|
0bb7fdd2eb | ||
|
|
650538ad2e | ||
|
|
b1debdf912 | ||
|
|
077de02345 | ||
|
|
163a770abc | ||
|
|
fc2a8e348c | ||
|
|
56278795ea | ||
|
|
a82f27ab8c | ||
|
|
2b8476ceca | ||
|
|
5ed4723535 | ||
|
|
b6aaa42337 | ||
|
|
e723604816 | ||
|
|
51ee9654da | ||
|
|
ea3fca3767 | ||
|
|
efad448fab | ||
|
|
018c993a9d | ||
|
|
863480acf2 | ||
|
|
ff12285e94 | ||
|
|
51b95f9cee | ||
|
|
86181525df | ||
|
|
85b6dc1766 | ||
|
|
bc7ad37e62 | ||
|
|
8042053331 | ||
|
|
0143dc25bf | ||
|
|
3e3ba60165 | ||
|
|
bd5c852fb6 | ||
|
|
a32f2d34f0 | ||
|
|
fee53e0ccf | ||
|
|
2eb58fb262 | ||
|
|
9ac6af95e3 | ||
|
|
b3da89d61c | ||
|
|
c91a79fe5b | ||
|
|
6771f59ab7 | ||
|
|
2faa2aeb95 | ||
|
|
04011a0a19 | ||
|
|
8ba3518fbc |
No files matched your search
+1
-1
@@ -1 +1 @@
|
||||
3.0
|
||||
3.1
|
||||
+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: xcode8
|
||||
osx_image: xcode8.3
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
|
||||
@@ -6,6 +6,7 @@ Socket.IO-client for iOS/OS X.
|
||||
##Example
|
||||
```swift
|
||||
import SocketIO
|
||||
|
||||
let socket = SocketIOClient(socketURL: URL(string: "http://localhost:8080")!, config: [.log(true), .forcePolling(true)])
|
||||
|
||||
socket.on("connect") {data, ack in
|
||||
@@ -14,7 +15,7 @@ socket.on("connect") {data, ack in
|
||||
|
||||
socket.on("currentAmount") {data, ack in
|
||||
if let cur = data[0] as? Double {
|
||||
socket.emitWithAck("canUpdate", cur)(0) {data in
|
||||
socket.emitWithAck("canUpdate", cur).timingOut(after: 0) {data in
|
||||
socket.emit("update", ["amount": cur + 2.50])
|
||||
}
|
||||
|
||||
@@ -38,9 +39,9 @@ SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:url config:@{
|
||||
[socket on:@"currentAmount" callback:^(NSArray* data, SocketAckEmitter* ack) {
|
||||
double cur = [[data objectAtIndex:0] floatValue];
|
||||
|
||||
[socket emitWithAck:@"canUpdate" withItems:@[@(cur)]](0, ^(NSArray* data) {
|
||||
[[socket emitWithAck:@"canUpdate" with:@[@(cur)]] timingOutAfter:0 callback:^(NSArray* data) {
|
||||
[socket emit:@"update" withItems:@[@{@"amount": @(cur + 2.50)}]];
|
||||
});
|
||||
}];
|
||||
|
||||
[ack with:@[@"Got your currentAmount, ", @"dude"]];
|
||||
}];
|
||||
@@ -59,7 +60,7 @@ SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:url config:@{
|
||||
##Installation
|
||||
Requires Swift 3/Xcode 8.x
|
||||
|
||||
If you need swift 2.3 use the swift2.3 branch (Pre-Swift 3 support is no longer maintained)
|
||||
If you need swift 2.3 use the swift2.3 tag (Pre-Swift 3 support is no longer maintained)
|
||||
|
||||
If you need swift 2.2 use 7.x (Pre-Swift 3 support is no longer maintained)
|
||||
|
||||
@@ -94,7 +95,7 @@ Carthage
|
||||
-----------------
|
||||
Add this line to your `Cartfile`:
|
||||
```
|
||||
github "socketio/socket.io-client-swift" ~> 8.0.1 # Or latest version
|
||||
github "socketio/socket.io-client-swift" ~> 8.3.2 # Or latest version
|
||||
```
|
||||
|
||||
Run `carthage update --platform ios,macosx`.
|
||||
@@ -107,7 +108,7 @@ Create `Podfile` and add `pod 'Socket.IO-Client-Swift'`:
|
||||
use_frameworks!
|
||||
|
||||
target 'YourApp' do
|
||||
pod 'Socket.IO-Client-Swift', '~> 8.0.1' # Or latest version
|
||||
pod 'Socket.IO-Client-Swift', '~> 8.3.2' # Or latest version
|
||||
end
|
||||
```
|
||||
|
||||
@@ -136,7 +137,7 @@ CocoaSeeds
|
||||
Add this line to your `Seedfile`:
|
||||
|
||||
```
|
||||
github "socketio/socket.io-client-swift", "v8.0.1", :files => "Source/*.swift" # Or latest version
|
||||
github "socketio/socket.io-client-swift", "v8.3.2", :files => "Source/*.swift" # Or latest version
|
||||
```
|
||||
|
||||
Run `seed install`.
|
||||
@@ -182,8 +183,8 @@ Methods
|
||||
3. `onAny(callback:((event: String, items: AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
|
||||
4. `emit(_ event: String, _ items: AnyObject...)` - Sends a message. Can send multiple items.
|
||||
5. `emit(_ event: String, withItems items: [AnyObject])` - `emit` for Objective-C
|
||||
6. `emitWithAck(_ event: String, _ items: AnyObject...) -> (timeoutAfter: UInt64, callback: (NSArray?) -> Void) -> Void` - Sends a message that requests an acknowledgement from the server. Returns a function which you can use to add a handler. See example. Note: The message is not sent until you call the returned function.
|
||||
7. `emitWithAck(_ event: String, withItems items: [AnyObject]) -> (UInt64, (NSArray?) -> Void) -> Void` - `emitWithAck` for Objective-C. Note: The message is not sent until you call the returned function.
|
||||
6. `emitWithAck(_ event: String, _ items: AnyObject...) -> OnAckCallback` - Sends a message that requests an acknowledgement from the server. Returns an object which you can use to add a handler. See example. Note: The message is not sent until you call timingOut(after:) on the returned object.
|
||||
7. `emitWithAck(_ event: String, withItems items: [AnyObject]) -> OnAckCallback` - `emitWithAck` for Objective-C. Note: The message is not sent until you call timingOutAfter on the returned object.
|
||||
8. `connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
|
||||
9. `connect(timeoutAfter timeoutAfter: Int, withTimeoutHandler handler: (() -> Void)?)` - Connect to the server. If it isn't connected after timeoutAfter seconds, the handler is called.
|
||||
10. `disconnect()` - Closes the socket. Reopening a disconnected socket is not fully tested.
|
||||
@@ -205,5 +206,7 @@ Client Events
|
||||
##Detailed Example
|
||||
A more detailed example can be found [here](https://github.com/nuclearace/socket.io-client-swift-example)
|
||||
|
||||
An example using the Swift Package Manager can be found [here](https://github.com/nuclearace/socket.io-client-swift-spm-example)
|
||||
|
||||
##License
|
||||
MIT
|
||||
@@ -1,7 +1,7 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "Socket.IO-Client-Swift"
|
||||
s.module_name = "SocketIO"
|
||||
s.version = "8.0.1"
|
||||
s.version = "8.3.2"
|
||||
s.summary = "Socket.IO-client for iOS and OS X"
|
||||
s.description = <<-DESC
|
||||
Socket.IO-client for iOS and OS X.
|
||||
@@ -14,8 +14,9 @@ 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 => 'v8.0.1' }
|
||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v8.3.2' }
|
||||
s.source_files = "Source/**/*.swift"
|
||||
s.requires_arc = true
|
||||
s.pod_target_xcconfig = {'SWIFT_VERSION' => '3.1'}
|
||||
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
|
||||
end
|
||||
@@ -82,8 +82,10 @@ class SocketEngineTest: XCTestCase {
|
||||
XCTAssertEqual(data[0] as? String, "lïne one\nlīne \rtwo", "Failed string test")
|
||||
expect.fulfill()
|
||||
}
|
||||
|
||||
|
||||
engine = SocketEngine(client: client, url: URL(string: "http://localhost")!, config: [.doubleEncodeUTF8(true)])
|
||||
engine.parsePollingMessage("41:42[\"stringTest\",\"lïne one\\nlīne \\rtwo\"]")
|
||||
|
||||
waitForExpectations(timeout: 3, handler: nil)
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
- (void)setUp {
|
||||
[super setUp];
|
||||
NSURL* url = [[NSURL alloc] initWithString:@"http://localhost"];
|
||||
self.socket = [[SocketIOClient alloc] initWithSocketURL:url config:nil];
|
||||
self.socket = [[SocketIOClient alloc] initWithSocketURL:url config:@{@"log": @YES, @"forcePolling": @YES}];
|
||||
}
|
||||
|
||||
- (void)testOnSyntax {
|
||||
@@ -35,9 +35,9 @@
|
||||
}
|
||||
|
||||
- (void)testEmitWithAckSyntax {
|
||||
[self.socket emitWithAck:@"testAckEmit" with:@[@YES]](0, ^(NSArray* data) {
|
||||
[[self.socket emitWithAck:@"testAckEmit" with:@[@YES]] timingOutAfter:0 callback:^(NSArray* data) {
|
||||
|
||||
});
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)testOffSyntax {
|
||||
|
||||
@@ -25,20 +25,20 @@ class SocketSideEffectTest: XCTestCase {
|
||||
}
|
||||
|
||||
func testFirstAck() {
|
||||
socket.emitWithAck("test")(0) {data in}
|
||||
socket.emitWithAck("test").timingOut(after: 0) {data in}
|
||||
XCTAssertEqual(socket.currentAck, 0)
|
||||
}
|
||||
|
||||
func testSecondAck() {
|
||||
socket.emitWithAck("test")(0) {data in}
|
||||
socket.emitWithAck("test")(0) {data in}
|
||||
socket.emitWithAck("test").timingOut(after: 0) {data in}
|
||||
socket.emitWithAck("test").timingOut(after: 0) {data in}
|
||||
|
||||
XCTAssertEqual(socket.currentAck, 1)
|
||||
}
|
||||
|
||||
func testHandleAck() {
|
||||
let expect = expectation(description: "handled ack")
|
||||
socket.emitWithAck("test")(0) {data in
|
||||
socket.emitWithAck("test").timingOut(after: 0) {data in
|
||||
XCTAssertEqual(data[0] as? String, "hello world")
|
||||
expect.fulfill()
|
||||
}
|
||||
@@ -49,7 +49,7 @@ class SocketSideEffectTest: XCTestCase {
|
||||
|
||||
func testHandleAck2() {
|
||||
let expect = expectation(description: "handled ack2")
|
||||
socket.emitWithAck("test")(0) {data in
|
||||
socket.emitWithAck("test").timingOut(after: 0) {data in
|
||||
XCTAssertTrue(data.count == 2, "Wrong number of ack items")
|
||||
expect.fulfill()
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Starscream
|
||||
//
|
||||
// Created by Dalton Cherry on 5/16/15.
|
||||
// Copyright (c) 2014-2015 Dalton Cherry.
|
||||
// Copyright (c) 2014-2016 Dalton Cherry.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
@@ -19,11 +19,14 @@
|
||||
// limitations under the License.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
import Foundation
|
||||
import Security
|
||||
|
||||
public class SSLCert : NSObject {
|
||||
public protocol SSLTrustValidator {
|
||||
func isValid(_ trust: SecTrust, domain: String?) -> Bool
|
||||
}
|
||||
|
||||
open class SSLCert : NSObject {
|
||||
var certData: Data?
|
||||
var key: SecKey?
|
||||
|
||||
@@ -50,12 +53,12 @@ public class SSLCert : NSObject {
|
||||
}
|
||||
}
|
||||
|
||||
public class SSLSecurity : NSObject {
|
||||
open class SSLSecurity : SSLTrustValidator {
|
||||
public var validatedDN = true //should the domain name be validated?
|
||||
|
||||
var isReady = false //is the key processing done?
|
||||
var certificates: [Data]? //the certificates
|
||||
var pubKeys: [SecKey]? //the public keys
|
||||
@nonobjc var pubKeys: [SecKey]? //the public keys
|
||||
var usePublicKeys = false //use public keys or certificate validation?
|
||||
|
||||
/**
|
||||
@@ -82,7 +85,7 @@ public class SSLSecurity : NSObject {
|
||||
/**
|
||||
Designated init
|
||||
|
||||
- parameter keys: is the certificates or public keys to use
|
||||
- parameter certs: is the certificates or public keys to use
|
||||
- parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
@@ -90,8 +93,6 @@ public class SSLSecurity : NSObject {
|
||||
public init(certs: [SSLCert], usePublicKeys: Bool) {
|
||||
self.usePublicKeys = usePublicKeys
|
||||
|
||||
super.init()
|
||||
|
||||
if self.usePublicKeys {
|
||||
DispatchQueue.global(qos: .default).async {
|
||||
let pubKeys = certs.reduce([SecKey]()) { (pubKeys: [SecKey], cert: SSLCert) -> [SecKey] in
|
||||
@@ -239,7 +240,7 @@ public class SSLSecurity : NSObject {
|
||||
|
||||
- returns: the public keys from the certifcate chain for the trust
|
||||
*/
|
||||
func publicKeyChain(_ trust: SecTrust) -> [SecKey] {
|
||||
@nonobjc func publicKeyChain(_ trust: SecTrust) -> [SecKey] {
|
||||
let policy = SecPolicyCreateBasicX509()
|
||||
let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKey]()) { (keys: [SecKey], index: Int) -> [SecKey] in
|
||||
var keys = keys
|
||||
|
||||
@@ -27,6 +27,10 @@ import Foundation
|
||||
public final class SocketAckEmitter : NSObject {
|
||||
let socket: SocketIOClient
|
||||
let ackNum: Int
|
||||
|
||||
public var expected: Bool {
|
||||
return ackNum != -1
|
||||
}
|
||||
|
||||
init(socket: SocketIOClient, ackNum: Int) {
|
||||
self.socket = socket
|
||||
@@ -44,4 +48,40 @@ public final class SocketAckEmitter : NSObject {
|
||||
|
||||
socket.emitAck(ackNum, with: items)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public final class OnAckCallback : NSObject {
|
||||
private let ackNumber: Int
|
||||
private let items: [Any]
|
||||
private weak var socket: SocketIOClient?
|
||||
|
||||
init(ackNumber: Int, items: [Any], socket: SocketIOClient) {
|
||||
self.ackNumber = ackNumber
|
||||
self.items = items
|
||||
self.socket = socket
|
||||
}
|
||||
|
||||
deinit {
|
||||
DefaultSocketLogger.Logger.log("OnAckCallback for \(ackNumber) being released", type: "OnAckCallback")
|
||||
}
|
||||
|
||||
public func timingOut(after seconds: Int, callback: @escaping AckCallback) {
|
||||
guard let socket = self.socket else { return }
|
||||
|
||||
socket.ackQueue.sync() {
|
||||
socket.ackHandlers.addAck(ackNumber, callback: callback)
|
||||
}
|
||||
|
||||
socket._emit(items, ack: ackNumber)
|
||||
|
||||
guard seconds != 0 else { return }
|
||||
|
||||
let time = DispatchTime.now() + Double(UInt64(seconds) * NSEC_PER_SEC) / Double(NSEC_PER_SEC)
|
||||
|
||||
socket.handleQueue.asyncAfter(deadline: time) {
|
||||
socket.ackHandlers.timeoutAck(self.ackNumber, onQueue: socket.handleQueue)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -51,6 +51,7 @@ private func ==(lhs: SocketAck, rhs: SocketAck) -> Bool {
|
||||
|
||||
struct SocketAckManager {
|
||||
private var acks = Set<SocketAck>(minimumCapacity: 1)
|
||||
private let ackSemaphore = DispatchSemaphore(value: 1)
|
||||
|
||||
mutating func addAck(_ ack: Int, callback: @escaping AckCallback) {
|
||||
acks.insert(SocketAck(ack: ack, callback: callback))
|
||||
@@ -58,6 +59,8 @@ struct SocketAckManager {
|
||||
|
||||
/// Should be called on handle queue
|
||||
mutating func executeAck(_ ack: Int, with items: [Any], onQueue: DispatchQueue) {
|
||||
ackSemaphore.wait()
|
||||
defer { ackSemaphore.signal() }
|
||||
let ack = acks.remove(SocketAck(ack: ack))
|
||||
|
||||
onQueue.async() { ack?.callback(items) }
|
||||
@@ -65,8 +68,12 @@ struct SocketAckManager {
|
||||
|
||||
/// Should be called on handle queue
|
||||
mutating func timeoutAck(_ ack: Int, onQueue: DispatchQueue) {
|
||||
ackSemaphore.wait()
|
||||
defer { ackSemaphore.signal() }
|
||||
let ack = acks.remove(SocketAck(ack: ack))
|
||||
|
||||
onQueue.async() { ack?.callback?(["NO ACK"]) }
|
||||
onQueue.async() {
|
||||
ack?.callback?(["NO ACK"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ public final class SocketAnyEvent : NSObject {
|
||||
public let event: String
|
||||
public let items: [Any]?
|
||||
override public var description: String {
|
||||
return "SocketAnyEvent: Event: \(event) items: \(items ?? nil)"
|
||||
return "SocketAnyEvent: Event: \(event) items: \(String(describing: items))"
|
||||
}
|
||||
|
||||
init(event: String, items: [Any]?) {
|
||||
|
||||
@@ -42,7 +42,7 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
|
||||
public private(set) var closed = false
|
||||
public private(set) var connected = false
|
||||
public private(set) var cookies: [HTTPCookie]?
|
||||
public private(set) var doubleEncodeUTF8 = true
|
||||
public private(set) var doubleEncodeUTF8 = false
|
||||
public private(set) var extraHeaders: [String: String]?
|
||||
public private(set) var fastUpgrade = false
|
||||
public private(set) var forcePolling = false
|
||||
@@ -372,6 +372,7 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
|
||||
|
||||
self.sid = sid
|
||||
connected = true
|
||||
pongsMissed = 0
|
||||
|
||||
if let upgrades = json["upgrades"] as? [String] {
|
||||
upgradeWs = upgrades.contains("websocket")
|
||||
|
||||
+19
-27
@@ -46,25 +46,27 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
|
||||
public var reconnects = true
|
||||
public var reconnectWait = 10
|
||||
|
||||
private let ackQueue = DispatchQueue(label: "com.socketio.ackQueue", attributes: [])
|
||||
private let emitQueue = DispatchQueue(label: "com.socketio.emitQueue", attributes: [])
|
||||
private let logType = "SocketIOClient"
|
||||
private let parseQueue = DispatchQueue(label: "com.socketio.parseQueue", attributes: [])
|
||||
private let parseQueue = DispatchQueue(label: "com.socketio.parseQueue")
|
||||
|
||||
private var anyHandler: ((SocketAnyEvent) -> Void)?
|
||||
private var currentReconnectAttempt = 0
|
||||
private var handlers = [SocketEventHandler]()
|
||||
private var ackHandlers = SocketAckManager()
|
||||
private var reconnecting = false
|
||||
|
||||
private let ackSemaphore = DispatchSemaphore(value: 1)
|
||||
private(set) var currentAck = -1
|
||||
private(set) var handleQueue = DispatchQueue.main
|
||||
private(set) var reconnectAttempts = -1
|
||||
|
||||
let ackQueue = DispatchQueue(label: "com.socketio.ackQueue")
|
||||
let emitQueue = DispatchQueue(label: "com.socketio.emitQueue")
|
||||
|
||||
var ackHandlers = SocketAckManager()
|
||||
var waitingPackets = [SocketPacket]()
|
||||
|
||||
public var sid: String? {
|
||||
return nsp + "#" + (engine?.sid ?? "")
|
||||
return engine?.sid
|
||||
}
|
||||
|
||||
/// Type safe way to create a new SocketIOClient. opts can be omitted
|
||||
@@ -148,7 +150,7 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
|
||||
|
||||
guard timeoutAfter != 0 else { return }
|
||||
|
||||
let time = DispatchTime.now() + Double(Int64(timeoutAfter) * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
|
||||
let time = DispatchTime.now() + Double(UInt64(timeoutAfter) * NSEC_PER_SEC) / Double(NSEC_PER_SEC)
|
||||
|
||||
handleQueue.asyncAfter(deadline: time) {[weak self] in
|
||||
guard let this = self, this.status != .connected && this.status != .disconnected else { return }
|
||||
@@ -160,27 +162,15 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
|
||||
}
|
||||
}
|
||||
|
||||
private func createOnAck(_ items: [Any]) -> OnAckCallback {
|
||||
private func nextAck() -> Int {
|
||||
ackSemaphore.wait()
|
||||
defer { ackSemaphore.signal() }
|
||||
currentAck += 1
|
||||
|
||||
return {[weak self, ack = currentAck] timeout, callback in
|
||||
guard let this = self else { return }
|
||||
return currentAck
|
||||
}
|
||||
|
||||
this.ackQueue.sync() {
|
||||
this.ackHandlers.addAck(ack, callback: callback)
|
||||
}
|
||||
|
||||
|
||||
this._emit(items, ack: ack)
|
||||
|
||||
if timeout != 0 {
|
||||
let time = DispatchTime.now() + Double(Int64(timeout * NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
|
||||
|
||||
this.handleQueue.asyncAfter(deadline: time) {
|
||||
this.ackHandlers.timeoutAck(ack, onQueue: this.handleQueue)
|
||||
}
|
||||
}
|
||||
}
|
||||
private func createOnAck(_ items: [Any]) -> OnAckCallback {
|
||||
return OnAckCallback(ackNumber: nextAck(), items: items, socket: self)
|
||||
}
|
||||
|
||||
func didConnect() {
|
||||
@@ -238,7 +228,7 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
|
||||
return createOnAck([event] + items)
|
||||
}
|
||||
|
||||
private func _emit(_ data: [Any], ack: Int? = nil) {
|
||||
func _emit(_ data: [Any], ack: Int? = nil) {
|
||||
emitQueue.async {
|
||||
guard self.status == .connected else {
|
||||
self.handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
|
||||
@@ -269,7 +259,9 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
|
||||
}
|
||||
|
||||
public func engineDidClose(reason: String) {
|
||||
waitingPackets.removeAll()
|
||||
parseQueue.async {
|
||||
self.waitingPackets.removeAll()
|
||||
}
|
||||
|
||||
if status != .disconnected {
|
||||
status = .notConnected
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
public struct SocketIOClientConfiguration : ExpressibleByArrayLiteral, Collection, MutableCollection {
|
||||
public typealias Element = SocketIOClientOption
|
||||
public typealias Index = Array<SocketIOClientOption>.Index
|
||||
public typealias Generator = Array<SocketIOClientOption>.Generator
|
||||
public typealias Generator = Array<SocketIOClientOption>.Iterator
|
||||
public typealias SubSequence = Array<SocketIOClientOption>.SubSequence
|
||||
|
||||
private var backingArray = [SocketIOClientOption]()
|
||||
|
||||
@@ -87,25 +87,18 @@ struct SocketPacket {
|
||||
}
|
||||
|
||||
private func completeMessage(_ message: String) -> String {
|
||||
let restOfMessage: String
|
||||
|
||||
if data.count == 0 {
|
||||
return message + "[]"
|
||||
}
|
||||
|
||||
do {
|
||||
let jsonSend = try data.toJSON()
|
||||
guard let jsonString = String(data: jsonSend, encoding: .utf8) else { return message + "[]" }
|
||||
|
||||
restOfMessage = jsonString
|
||||
} catch {
|
||||
guard let jsonSend = try? data.toJSON(), let jsonString = String(data: jsonSend, encoding: .utf8) else {
|
||||
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
|
||||
type: SocketPacket.logType)
|
||||
type: SocketPacket.logType)
|
||||
|
||||
restOfMessage = "[]"
|
||||
return message + "[]"
|
||||
}
|
||||
|
||||
return message + restOfMessage
|
||||
return message + jsonString
|
||||
}
|
||||
|
||||
private func createPacketString() -> String {
|
||||
@@ -133,11 +126,11 @@ struct SocketPacket {
|
||||
// binary data
|
||||
private func _fillInPlaceholders(_ object: Any) -> Any {
|
||||
switch object {
|
||||
case let dict as [String: Any]:
|
||||
case let dict as JSON:
|
||||
if dict["_placeholder"] as? Bool ?? false {
|
||||
return binary[dict["num"] as! Int]
|
||||
} else {
|
||||
return dict.reduce([String: Any](), {cur, keyValue in
|
||||
return dict.reduce(JSON(), {cur, keyValue in
|
||||
var cur = cur
|
||||
|
||||
cur[keyValue.0] = _fillInPlaceholders(keyValue.1)
|
||||
@@ -181,7 +174,7 @@ extension SocketPacket {
|
||||
private extension SocketPacket {
|
||||
// Recursive function that looks for NSData in collections
|
||||
static func shred(_ data: Any, binary: inout [Data]) -> Any {
|
||||
let placeholder = ["_placeholder": true, "num": binary.count] as [String : Any]
|
||||
let placeholder = ["_placeholder": true, "num": binary.count] as JSON
|
||||
|
||||
switch data {
|
||||
case let bin as Data:
|
||||
@@ -190,8 +183,8 @@ private extension SocketPacket {
|
||||
return placeholder
|
||||
case let arr as [Any]:
|
||||
return arr.map({shred($0, binary: &binary)})
|
||||
case let dict as [String: Any]:
|
||||
return dict.reduce([String: Any](), {cur, keyValue in
|
||||
case let dict as JSON:
|
||||
return dict.reduce(JSON(), {cur, keyValue in
|
||||
var mutCur = cur
|
||||
|
||||
mutCur[keyValue.0] = shred(keyValue.1, binary: &binary)
|
||||
|
||||
@@ -41,8 +41,8 @@ extension String : SocketData {}
|
||||
|
||||
public typealias AckCallback = ([Any]) -> Void
|
||||
public typealias NormalCallback = ([Any], SocketAckEmitter) -> Void
|
||||
public typealias OnAckCallback = (_ timeoutAfter: UInt64, _ callback: @escaping AckCallback) -> Void
|
||||
|
||||
typealias JSON = [String: Any]
|
||||
typealias Probe = (msg: String, type: SocketEnginePacketType, data: [Data])
|
||||
typealias ProbeWaitQueue = [Probe]
|
||||
|
||||
|
||||
+140
-116
@@ -3,7 +3,7 @@
|
||||
// Websocket.swift
|
||||
//
|
||||
// Created by Dalton Cherry on 7/16/14.
|
||||
// Copyright (c) 2014-2015 Dalton Cherry.
|
||||
// Copyright (c) 2014-2016 Dalton Cherry.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
@@ -18,7 +18,6 @@
|
||||
// limitations under the License.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
import Foundation
|
||||
import CoreFoundation
|
||||
import Security
|
||||
@@ -38,7 +37,7 @@ public protocol WebSocketPongDelegate: class {
|
||||
func websocketDidReceivePong(socket: WebSocket, data: Data?)
|
||||
}
|
||||
|
||||
public class WebSocket : NSObject, StreamDelegate {
|
||||
open class WebSocket : NSObject, StreamDelegate {
|
||||
|
||||
enum OpCode : UInt8 {
|
||||
case continueFrame = 0x0
|
||||
@@ -77,7 +76,6 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
var optionalProtocols: [String]?
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
let headerWSUpgradeName = "Upgrade"
|
||||
let headerWSUpgradeValue = "websocket"
|
||||
let headerWSHostName = "Host"
|
||||
@@ -108,7 +106,6 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
}
|
||||
|
||||
// MARK: - Delegates
|
||||
|
||||
/// Responds to callback about new messages coming in over the WebSocket
|
||||
/// and also connection/disconnect messages.
|
||||
public weak var delegate: WebSocketDelegate?
|
||||
@@ -118,7 +115,6 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
|
||||
|
||||
// MARK: - Block based API.
|
||||
|
||||
public var onConnect: ((Void) -> Void)?
|
||||
public var onDisconnect: ((NSError?) -> Void)?
|
||||
public var onText: ((String) -> Void)?
|
||||
@@ -128,7 +124,7 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
public var headers = [String: String]()
|
||||
public var voipEnabled = false
|
||||
public var disableSSLCertValidation = false
|
||||
public var security: SSLSecurity?
|
||||
public var security: SSLTrustValidator?
|
||||
public var enabledSSLCipherSuites: [SSLCipherSuite]?
|
||||
public var origin: String?
|
||||
public var timeout = 5
|
||||
@@ -139,7 +135,6 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
public var currentURL: URL { return url }
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private var url: URL
|
||||
private var inputStream: InputStream?
|
||||
private var outputStream: OutputStream?
|
||||
@@ -167,6 +162,11 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
public init(url: URL, protocols: [String]? = nil) {
|
||||
self.url = url
|
||||
self.origin = url.absoluteString
|
||||
if let hostUrl = URL (string: "/", relativeTo: url) {
|
||||
var origin = hostUrl.absoluteString
|
||||
origin.remove(at: origin.index(before: origin.endIndex))
|
||||
self.origin = origin
|
||||
}
|
||||
writeQueue.maxConcurrentOperationCount = 1
|
||||
optionalProtocols = protocols
|
||||
}
|
||||
@@ -180,12 +180,11 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
/**
|
||||
Connect to the WebSocket server on a background thread.
|
||||
*/
|
||||
public func connect() {
|
||||
open func connect() {
|
||||
guard !isConnecting else { return }
|
||||
didDisconnect = false
|
||||
isConnecting = true
|
||||
createHTTPRequest()
|
||||
isConnecting = false
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -195,10 +194,12 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
- Parameter forceTimeout: Maximum time to wait for the server to close the socket.
|
||||
- Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket.
|
||||
*/
|
||||
public func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) {
|
||||
open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) {
|
||||
guard isConnected else { return }
|
||||
switch forceTimeout {
|
||||
case .some(let seconds) where seconds > 0:
|
||||
callbackQueue.asyncAfter(deadline: DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { [weak self] in
|
||||
let milliseconds = Int(seconds * 1_000)
|
||||
callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in
|
||||
self?.disconnectStream(nil)
|
||||
}
|
||||
fallthrough
|
||||
@@ -213,10 +214,10 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
/**
|
||||
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 string: The string to write.
|
||||
- parameter completion: The (optional) completion handler.
|
||||
*/
|
||||
public func write(string: String, completion: (() -> ())? = nil) {
|
||||
open func write(string: String, completion: (() -> ())? = nil) {
|
||||
guard isConnected else { return }
|
||||
dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion)
|
||||
}
|
||||
@@ -227,7 +228,7 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
- parameter data: The data to write.
|
||||
- parameter completion: The (optional) completion handler.
|
||||
*/
|
||||
public func write(data: Data, completion: (() -> ())? = nil) {
|
||||
open func write(data: Data, completion: (() -> ())? = nil) {
|
||||
guard isConnected else { return }
|
||||
dequeueWrite(data, code: .binaryFrame, writeCompletion: completion)
|
||||
}
|
||||
@@ -236,7 +237,7 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
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 write(ping: Data, completion: (() -> ())? = nil) {
|
||||
open func write(ping: Data, completion: (() -> ())? = nil) {
|
||||
guard isConnected else { return }
|
||||
dequeueWrite(ping, code: .ping, writeCompletion: completion)
|
||||
}
|
||||
@@ -245,7 +246,6 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
Private method that starts the connection.
|
||||
*/
|
||||
private func createHTTPRequest() {
|
||||
|
||||
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET" as CFString,
|
||||
url as CFURL, kCFHTTPVersion1_1).takeRetainedValue()
|
||||
|
||||
@@ -305,6 +305,8 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
private func initStreamsWithData(_ data: Data, _ port: Int) {
|
||||
//higher level API we will cut over to at some point
|
||||
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
|
||||
// Disconnect and clean up any existing streams before setting up a new pair
|
||||
disconnectStream(nil, runDelegate: false)
|
||||
|
||||
var readStream: Unmanaged<CFReadStream>?
|
||||
var writeStream: Unmanaged<CFWriteStream>?
|
||||
@@ -316,8 +318,31 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
inStream.delegate = self
|
||||
outStream.delegate = self
|
||||
if supportedSSLSchemes.contains(url.scheme!) {
|
||||
certValidated = false
|
||||
inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
|
||||
outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
|
||||
if disableSSLCertValidation {
|
||||
let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(value: false), kCFStreamSSLPeerName: kCFNull]
|
||||
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
|
||||
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
|
||||
}
|
||||
if let cipherSuites = self.enabledSSLCipherSuites {
|
||||
if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?,
|
||||
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
certValidated = true //not a https session, so no need to check SSL pinning
|
||||
}
|
||||
@@ -325,28 +350,6 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
inStream.setProperty(StreamNetworkServiceTypeValue.voIP as AnyObject, forKey: Stream.PropertyKey.networkServiceType)
|
||||
outStream.setProperty(StreamNetworkServiceTypeValue.voIP as AnyObject, forKey: Stream.PropertyKey.networkServiceType)
|
||||
}
|
||||
if disableSSLCertValidation {
|
||||
let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(value: false), kCFStreamSSLPeerName: kCFNull]
|
||||
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
|
||||
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
|
||||
}
|
||||
if let cipherSuites = self.enabledSSLCipherSuites {
|
||||
if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?,
|
||||
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
|
||||
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)
|
||||
CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue)
|
||||
@@ -358,38 +361,47 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
self.mutex.unlock()
|
||||
|
||||
let bytes = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self)
|
||||
var out = timeout * 1000000 // wait 5 seconds before giving up
|
||||
writeQueue.addOperation { [weak self] in
|
||||
while !outStream.hasSpaceAvailable {
|
||||
var out = timeout * 1_000_000 // wait 5 seconds before giving up
|
||||
let operation = BlockOperation()
|
||||
operation.addExecutionBlock { [weak self, weak operation] in
|
||||
guard let sOperation = operation else { return }
|
||||
while !outStream.hasSpaceAvailable && !sOperation.isCancelled {
|
||||
usleep(100) // wait until the socket is ready
|
||||
guard !sOperation.isCancelled else { return }
|
||||
out -= 100
|
||||
if out < 0 {
|
||||
self?.cleanupStream()
|
||||
WebSocket.sharedWorkQueue.async {
|
||||
self?.cleanupStream()
|
||||
}
|
||||
self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2))
|
||||
return
|
||||
} else if outStream.streamError != nil {
|
||||
return // disconnectStream will be called.
|
||||
}
|
||||
}
|
||||
guard !sOperation.isCancelled, let s = self else { return }
|
||||
// Do the pinning now if needed
|
||||
if let sec = s.security, !s.certValidated {
|
||||
let trust = outStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust
|
||||
let domain = outStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String
|
||||
s.certValidated = sec.isValid(trust, domain: domain)
|
||||
if !s.certValidated {
|
||||
WebSocket.sharedWorkQueue.async {
|
||||
let error = s.errorWithDetail("Invalid SSL certificate", code: 1)
|
||||
s.disconnectStream(error)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
outStream.write(bytes, maxLength: data.count)
|
||||
}
|
||||
writeQueue.addOperation(operation)
|
||||
}
|
||||
|
||||
/**
|
||||
Delegate for the stream methods. Processes incoming bytes
|
||||
*/
|
||||
public func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
|
||||
if let sec = security, !certValidated && [.hasBytesAvailable, .hasSpaceAvailable].contains(eventCode) {
|
||||
let trust = aStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as AnyObject
|
||||
let domain = aStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String
|
||||
if sec.isValid(trust as! SecTrust, domain: domain) {
|
||||
certValidated = true
|
||||
} else {
|
||||
let error = errorWithDetail("Invalid SSL certificate", code: 1)
|
||||
disconnectStream(error)
|
||||
return
|
||||
}
|
||||
}
|
||||
open func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
|
||||
if eventCode == .hasBytesAvailable {
|
||||
if aStream == inputStream {
|
||||
processInputStream()
|
||||
@@ -404,14 +416,17 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
/**
|
||||
Disconnect the stream object and notifies the delegate.
|
||||
*/
|
||||
private func disconnectStream(_ error: NSError?) {
|
||||
private func disconnectStream(_ error: NSError?, runDelegate: Bool = true) {
|
||||
if error == nil {
|
||||
writeQueue.waitUntilAllOperationsAreFinished()
|
||||
} else {
|
||||
writeQueue.cancelAllOperations()
|
||||
}
|
||||
cleanupStream()
|
||||
doDisconnect(error)
|
||||
connected = false
|
||||
if runDelegate {
|
||||
doDisconnect(error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -430,6 +445,7 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
}
|
||||
outputStream = nil
|
||||
inputStream = nil
|
||||
fragBuffer = nil
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -439,7 +455,6 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
let buf = NSMutableData(capacity: BUFFER_MAX)
|
||||
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
|
||||
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
|
||||
|
||||
guard length > 0 else { return }
|
||||
var process = false
|
||||
if inputQueue.count == 0 {
|
||||
@@ -456,22 +471,24 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
*/
|
||||
private func dequeueInput() {
|
||||
while !inputQueue.isEmpty {
|
||||
let data = inputQueue[0]
|
||||
var work = data
|
||||
if let fragBuffer = fragBuffer {
|
||||
var combine = NSData(data: fragBuffer) as Data
|
||||
combine.append(data)
|
||||
work = combine
|
||||
self.fragBuffer = nil
|
||||
autoreleasepool {
|
||||
let data = inputQueue[0]
|
||||
var work = data
|
||||
if let buffer = fragBuffer {
|
||||
var combine = NSData(data: buffer) as Data
|
||||
combine.append(data)
|
||||
work = combine
|
||||
fragBuffer = nil
|
||||
}
|
||||
let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self)
|
||||
let length = work.count
|
||||
if !connected {
|
||||
processTCPHandshake(buffer, bufferLen: length)
|
||||
} else {
|
||||
processRawMessagesInBuffer(buffer, bufferLen: length)
|
||||
}
|
||||
inputQueue = inputQueue.filter{ $0 != data }
|
||||
}
|
||||
let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self)
|
||||
let length = work.count
|
||||
if !connected {
|
||||
processTCPHandshake(buffer, bufferLen: length)
|
||||
} else {
|
||||
processRawMessagesInBuffer(buffer, bufferLen: length)
|
||||
}
|
||||
inputQueue = inputQueue.filter{ $0 != data }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,14 +499,7 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
let code = processHTTP(buffer, bufferLen: bufferLen)
|
||||
switch code {
|
||||
case 0:
|
||||
connected = true
|
||||
guard canDispatch else {return}
|
||||
callbackQueue.async { [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.onConnect?()
|
||||
s.delegate?.websocketDidConnect(socket: s)
|
||||
s.notificationCenter.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self)
|
||||
}
|
||||
break
|
||||
case -1:
|
||||
fragBuffer = Data(bytes: buffer, count: bufferLen)
|
||||
break // do nothing, we are going to collect more data
|
||||
@@ -521,6 +531,17 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
if code != 0 {
|
||||
return code
|
||||
}
|
||||
isConnecting = false
|
||||
connected = true
|
||||
didDisconnect = false
|
||||
if canDispatch {
|
||||
callbackQueue.async { [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.onConnect?()
|
||||
s.delegate?.websocketDidConnect(socket: s)
|
||||
s.notificationCenter.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self)
|
||||
}
|
||||
}
|
||||
totalSize += 1 //skip the last \n
|
||||
let restSize = bufferLen - totalSize
|
||||
if restSize > 0 {
|
||||
@@ -611,7 +632,8 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
return buffer.fromOffset(bufferLen - extra)
|
||||
} else {
|
||||
let isFin = (FinMask & baseAddress[0])
|
||||
let receivedOpcode = OpCode(rawValue: (OpCodeMask & baseAddress[0]))
|
||||
let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0])
|
||||
let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue)
|
||||
let isMasked = (MaskMask & baseAddress[1])
|
||||
let payloadLen = (PayloadLenMask & baseAddress[1])
|
||||
var offset = 2
|
||||
@@ -625,7 +647,7 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame &&
|
||||
receivedOpcode != .textFrame && receivedOpcode != .pong) {
|
||||
let errCode = CloseCode.protocolError.rawValue
|
||||
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
|
||||
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcodeRawValue)", code: errCode))
|
||||
writeError(errCode)
|
||||
return emptyBuffer
|
||||
}
|
||||
@@ -635,34 +657,22 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
writeError(errCode)
|
||||
return emptyBuffer
|
||||
}
|
||||
var closeCode = CloseCode.normal.rawValue
|
||||
if receivedOpcode == .connectionClose {
|
||||
var code = CloseCode.normal.rawValue
|
||||
if payloadLen == 1 {
|
||||
code = CloseCode.protocolError.rawValue
|
||||
closeCode = CloseCode.protocolError.rawValue
|
||||
} else if payloadLen > 1 {
|
||||
code = WebSocket.readUint16(baseAddress, offset: offset)
|
||||
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
|
||||
code = CloseCode.protocolError.rawValue
|
||||
}
|
||||
offset += 2
|
||||
}
|
||||
var closeReason = "connection closed by server"
|
||||
if payloadLen > 2 {
|
||||
let len = Int(payloadLen - 2)
|
||||
if len > 0 {
|
||||
let bytes = baseAddress + offset
|
||||
if let customCloseReason = String(data: Data(bytes: bytes, count: len), encoding: .utf8) {
|
||||
closeReason = customCloseReason
|
||||
} else {
|
||||
code = CloseCode.protocolError.rawValue
|
||||
}
|
||||
closeCode = WebSocket.readUint16(baseAddress, offset: offset)
|
||||
if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1011 && closeCode < 3000) {
|
||||
closeCode = CloseCode.protocolError.rawValue
|
||||
}
|
||||
}
|
||||
doDisconnect(errorWithDetail(closeReason, code: code))
|
||||
writeError(code)
|
||||
return emptyBuffer
|
||||
}
|
||||
if isControlFrame && payloadLen > 125 {
|
||||
if payloadLen < 2 {
|
||||
doDisconnect(errorWithDetail("connection closed by server", code: closeCode))
|
||||
writeError(closeCode)
|
||||
return emptyBuffer
|
||||
}
|
||||
} else if isControlFrame && payloadLen > 125 {
|
||||
writeError(CloseCode.protocolError.rawValue)
|
||||
return emptyBuffer
|
||||
}
|
||||
@@ -682,12 +692,23 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
if dataLength > UInt64(bufferLen) {
|
||||
len = UInt64(bufferLen-offset)
|
||||
}
|
||||
let data: Data
|
||||
if len < 0 {
|
||||
len = 0
|
||||
data = Data()
|
||||
} else {
|
||||
data = Data(bytes: baseAddress+offset, count: Int(len))
|
||||
if receivedOpcode == .connectionClose && len > 0 {
|
||||
let size = MemoryLayout<UInt16>.size
|
||||
offset += size
|
||||
len -= UInt64(size)
|
||||
}
|
||||
let data = Data(bytes: baseAddress+offset, count: Int(len))
|
||||
|
||||
if receivedOpcode == .connectionClose {
|
||||
var closeReason = "connection closed by server"
|
||||
if let customCloseReason = String(data: data, encoding: .utf8) {
|
||||
closeReason = customCloseReason
|
||||
} else {
|
||||
closeCode = CloseCode.protocolError.rawValue
|
||||
}
|
||||
doDisconnect(errorWithDetail(closeReason, code: closeCode))
|
||||
writeError(closeCode)
|
||||
return emptyBuffer
|
||||
}
|
||||
if receivedOpcode == .pong {
|
||||
if canDispatch {
|
||||
@@ -824,9 +845,11 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
Used to write things to the stream
|
||||
*/
|
||||
private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) {
|
||||
writeQueue.addOperation { [weak self] in
|
||||
let operation = BlockOperation()
|
||||
operation.addExecutionBlock { [weak self, weak operation] in
|
||||
//stream isn't ready, let's wait
|
||||
guard let s = self else { return }
|
||||
guard let sOperation = operation else { return }
|
||||
var offset = 2
|
||||
let dataLength = data.count
|
||||
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
|
||||
@@ -853,7 +876,7 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
offset += 1
|
||||
}
|
||||
var total = 0
|
||||
while true {
|
||||
while !sOperation.isCancelled {
|
||||
guard let outStream = s.outputStream else { break }
|
||||
let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self)
|
||||
let len = outStream.write(writeBuffer, maxLength: offset-total)
|
||||
@@ -880,8 +903,8 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
writeQueue.addOperation(operation)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -890,6 +913,7 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
private func doDisconnect(_ error: NSError?) {
|
||||
guard !didDisconnect else { return }
|
||||
didDisconnect = true
|
||||
isConnecting = false
|
||||
connected = false
|
||||
guard canDispatch else {return}
|
||||
callbackQueue.async { [weak self] in
|
||||
@@ -902,12 +926,12 @@ public class WebSocket : NSObject, StreamDelegate {
|
||||
}
|
||||
|
||||
// MARK: - Deinit
|
||||
|
||||
deinit {
|
||||
mutex.lock()
|
||||
readyToWrite = false
|
||||
mutex.unlock()
|
||||
cleanupStream()
|
||||
writeQueue.cancelAllOperations()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user