Compare commits

...
47 Commits
Author SHA1 Message Date
Erik 551ad7f6af bump version 2017-03-08 19:56:48 -05:00
Erik b3fd4203d2 Merge branch 'development'
* development:
  SocketAckManager thread-safe acks removal
  thread-safe ack generation
  bump websocket
  Fix building on xcode8.3
  double encoding should be getting fixed, make the default false
  bump websocket
2017-03-08 19:55:46 -05:00
Erik Little c462381587 Merge pull request #629 from Sistemium/development
SocketAckManager thread-safe acks removal
2017-03-07 10:17:52 -05:00
Alexander Levin 99faafe723 SocketAckManager thread-safe acks removal 2017-03-06 19:57:19 +02:00
Erik Little efefecdbe3 Merge pull request #622 from Sistemium/development
thread-safe ack generation
2017-02-23 18:50:36 -05:00
Alexander Levin fcb2b6bbf6 thread-safe ack generation 2017-02-23 09:32:50 +02:00
Erik cce88ae3eb bump websocket 2017-02-12 12:13:21 -05:00
Erik Little 1616a58bd7 Fix building on xcode8.3 2017-01-30 12:13:02 -05:00
Erik 0fcb7903bb double encoding should be getting fixed, make the default false 2017-01-23 16:48:37 -05:00
Erik 3db37023c7 Merge branch 'master' into development
* master:
  Update SocketEngine.swift
  Update SocketEngine.swift
2017-01-23 16:44:02 -05:00
Erik Little e38bda7239 Merge pull request #602 from mephi1984/patch-1
Update SocketEngine.swift
2017-01-23 08:47:49 -05:00
Erik 9a05f794f7 bump websocket 2016-12-30 19:49:23 -05:00
Vladislav Khorev f943f41895 Update SocketEngine.swift
Fix issue #101
Place code in handleOpen, according to suggestion:
https://github.com/socketio/socket.io-client-swift/pull/602#issuecomment-269233001
2016-12-30 19:49:48 +03:00
Vladislav Khorev 494f3fa199 Update SocketEngine.swift
Fix issue #101
https://github.com/socketio/socket.io-client-swift/issues/101
2016-12-26 12:40:14 +03:00
Erik 0bb7fdd2eb bump version 2016-12-18 20:19:09 -05:00
Erik 650538ad2e Merge branch 'development'
* development:
  bump ws, fix #598
  remove namespace from socket id
2016-12-18 20:17:51 -05:00
Erik b1debdf912 bump ws, fix #598 2016-12-18 20:06:12 -05:00
Erik 077de02345 remove namespace from socket id 2016-11-24 08:15:17 -05:00
Erik 163a770abc bump version 2016-11-11 15:55:48 -05:00
Erik fc2a8e348c Merge branch 'development'
* development:
  Fix #562
2016-11-11 15:53:58 -05:00
Erik 56278795ea Merge branch 'development' of https://github.com/socketio/socket.io-client-swift into development
* 'development' of https://github.com/socketio/socket.io-client-swift:
  SocketAckEmitter.isExpected => .expected
  change isRequired() to isExpected()
  remove semicolon
  Update README.md
  add SocketAckEmitter.isRequired()
  Update README.md
  bump version
  bump websocket version
  fix Use Legacy Swift issue
  bump websocket version
  Update README.md
2016-11-11 15:52:48 -05:00
Erik a82f27ab8c Fix #562 2016-11-11 15:52:36 -05:00
Erik Little 2b8476ceca bump version 2016-10-28 11:53:02 -04:00
Erik Little 5ed4723535 Merge branch 'development'
* development:
  SocketAckEmitter.isExpected => .expected
  change isRequired() to isExpected()
  remove semicolon
  add SocketAckEmitter.isRequired()
  fix Use Legacy Swift issue
2016-10-28 11:51:58 -04:00
Erik Little b6aaa42337 Merge branch 'master' into development
* master:
  Update README.md
2016-10-28 11:51:46 -04:00
Erik Little e723604816 Merge pull request #544 from alexsun/patch-1
fix Use Legacy Swift issue
2016-10-28 11:46:46 -04:00
Erik Little 51ee9654da Merge pull request #557 from naderio/master
add SocketAckEmitter.expected to indicate if an ack is expected by server
2016-10-28 11:17:30 -04:00
Nader Toukabri ea3fca3767 SocketAckEmitter.isExpected => .expected 2016-10-28 15:59:50 +01:00
Nader Toukabri efad448fab change isRequired() to isExpected() 2016-10-28 15:14:07 +01:00
Nader Toukabri 018c993a9d remove semicolon 2016-10-28 15:09:21 +01:00
Erik Little 863480acf2 Update README.md 2016-10-28 09:43:46 -04:00
Nader Toukabri ff12285e94 add SocketAckEmitter.isRequired() 2016-10-28 14:23:22 +01:00
Nader Toukabri 51b95f9cee Merge pull request #1 from socketio/master
sync
2016-10-28 12:56:33 +01:00
Erik Little 86181525df Update README.md 2016-10-27 07:14:53 -04:00
Erik Little 85b6dc1766 bump version 2016-10-27 07:02:01 -04:00
Erik Little bc7ad37e62 Merge branch 'development'
* development:
  bump websocket version
  bump websocket version
  Fix #521
  add options to objective-c test
  add link to spm example
  remove redundant cast
  remove redundant cast
  Redo emitWithAck API since in Swift 3 parameter names aren't apart of the type
2016-10-27 06:38:56 -04:00
Erik Little 8042053331 bump websocket version 2016-10-27 06:37:39 -04:00
Jin Sun 0143dc25bf fix Use Legacy Swift issue 2016-10-18 17:29:01 +08:00
Erik Little 3e3ba60165 bump websocket version 2016-10-12 11:55:44 -04:00
Erik Little bd5c852fb6 Update README.md 2016-10-05 08:56:22 -04:00
Erik a32f2d34f0 Fix #521 2016-10-01 10:20:13 -04:00
Erik fee53e0ccf add options to objective-c test 2016-09-26 20:39:38 -04:00
Erik 2eb58fb262 add link to spm example 2016-09-25 14:51:54 -04:00
Erik 9ac6af95e3 Merge branch 'master' into development
* master:
  bump version
2016-09-25 13:39:14 -04:00
Erik b3da89d61c remove redundant cast 2016-09-25 12:10:29 -04:00
Erik c91a79fe5b remove redundant cast 2016-09-25 12:07:55 -04:00
Erik 6771f59ab7 Redo emitWithAck API since in Swift 3 parameter names aren't apart of the type 2016-09-25 11:59:10 -04:00
14 changed files with 302 additions and 239 deletions

No files matched your search

+11 -8
View File
@@ -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"]];
}];
@@ -94,7 +95,7 @@ Carthage
-----------------
Add this line to your `Cartfile`:
```
github "socketio/socket.io-client-swift" ~> 8.0.2 # Or latest version
github "socketio/socket.io-client-swift" ~> 8.3.0 # 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.2' # Or latest version
pod 'Socket.IO-Client-Swift', '~> 8.3.0' # Or latest version
end
```
@@ -136,7 +137,7 @@ CocoaSeeds
Add this line to your `Seedfile`:
```
github "socketio/socket.io-client-swift", "v8.0.2", :files => "Source/*.swift" # Or latest version
github "socketio/socket.io-client-swift", "v8.3.0", :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
+3 -2
View File
@@ -1,7 +1,7 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.module_name = "SocketIO"
s.version = "8.0.2"
s.version = "8.3.0"
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.2' }
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v8.3.0' }
s.source_files = "Source/**/*.swift"
s.requires_arc = true
s.pod_target_xcconfig = {'SWIFT_VERSION' => '3.0'}
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
end
+3 -1
View File
@@ -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)
}
+3 -3
View File
@@ -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 {
+5 -5
View File
@@ -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()
}
+8 -7
View File
@@ -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,7 +53,7 @@ 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?
@@ -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
+40
View File
@@ -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)
}
}
}
+8 -1
View File
@@ -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"])
}
}
}
+2 -1
View File
@@ -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
View File
@@ -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
+1 -1
View File
@@ -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]()
+9 -16
View File
@@ -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)
+1 -1
View File
@@ -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]
+189 -166
View File
@@ -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,8 +37,8 @@ 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
case textFrame = 0x1
@@ -50,7 +49,7 @@ public class WebSocket : NSObject, StreamDelegate {
case pong = 0xA
// B-F reserved.
}
public enum CloseCode : UInt16 {
case normal = 1000
case goingAway = 1001
@@ -63,21 +62,20 @@ public class WebSocket : NSObject, StreamDelegate {
case policyViolated = 1008
case messageTooBig = 1009
}
public static let ErrorDomain = "WebSocket"
enum InternalErrorCode: UInt16 {
// 0-999 WebSocket status codes not used
case outputStreamWriteError = 1
}
// Where the callback is executed. It defaults to the main UI thread queue.
public var callbackQueue = DispatchQueue.main
var optionalProtocols: [String]?
// MARK: - Constants
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
@@ -98,7 +96,7 @@ public class WebSocket : NSObject, StreamDelegate {
let MaxFrameSize: Int = 32
let httpSwitchProtocolCode = 101
let supportedSSLSchemes = ["wss", "https"]
class WSResponse {
var isFin = false
var code: OpCode = .continueFrame
@@ -106,40 +104,37 @@ public class WebSocket : NSObject, StreamDelegate {
var frameCount = 0
var buffer: NSMutableData?
}
// MARK: - Delegates
/// Responds to callback about new messages coming in over the WebSocket
/// and also connection/disconnect messages.
public weak var delegate: WebSocketDelegate?
/// Receives a callback for each pong message recived.
public weak var pongDelegate: WebSocketPongDelegate?
// MARK: - Block based API.
public var onConnect: ((Void) -> Void)?
public var onDisconnect: ((NSError?) -> Void)?
public var onText: ((String) -> Void)?
public var onData: ((Data) -> Void)?
public var onPong: ((Data?) -> Void)?
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
public var isConnected: Bool {
return connected
}
public var currentURL: URL { return url }
// MARK: - Private
private var url: URL
private var inputStream: InputStream?
private var outputStream: OutputStream?
@@ -162,43 +157,49 @@ public class WebSocket : NSObject, StreamDelegate {
}
/// The shared processing queue used for all WebSocket.
private static let sharedWorkQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: [])
/// Used for setting protocols.
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
}
// Used for specifically setting the QOS for the write queue.
public convenience init(url: URL, writeQueueQOS: QualityOfService, protocols: [String]? = nil) {
self.init(url: url, protocols: protocols)
writeQueue.qualityOfService = writeQueueQOS
}
/**
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
}
/**
Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed.
If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate.
If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate.
- 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
@@ -209,46 +210,46 @@ public class WebSocket : NSObject, StreamDelegate {
break
}
}
/**
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)
}
/**
Write binary data to the websocket. This sends it as a binary frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter data: The data to write.
- parameter completion: The (optional) completion handler.
*/
public func write(data: Data, completion: (() -> ())? = nil) {
open func write(data: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .binaryFrame, writeCompletion: completion)
}
/**
Write a ping to the websocket. This sends it as a control frame.
Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
*/
public func write(ping: Data, completion: (() -> ())? = nil) {
open func write(ping: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(ping, code: .ping, writeCompletion: completion)
}
/**
Private method that starts the connection.
*/
private func createHTTPRequest() {
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET" as CFString,
url as CFURL, kCFHTTPVersion1_1).takeRetainedValue()
var port = url.port
if port == nil {
if supportedSSLSchemes.contains(url.scheme!) {
@@ -276,14 +277,14 @@ public class WebSocket : NSObject, StreamDelegate {
initStreamsWithData(serializedRequest as Data, Int(port!))
}
}
/**
Add a header to the CFHTTPMessage by using the NSString bridges to CFString
*/
private func addHeader(_ urlRequest: CFHTTPMessage, key: String, val: String) {
CFHTTPMessageSetHeaderFieldValue(urlRequest, key as CFString, val as CFString)
}
/**
Generate a WebSocket key as needed in RFC.
*/
@@ -298,14 +299,16 @@ public class WebSocket : NSObject, StreamDelegate {
let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
return baseKey!
}
/**
Start the stream connection and write the data to the output stream.
*/
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>?
let h = url.host! as NSString
@@ -318,6 +321,28 @@ public class WebSocket : NSObject, StreamDelegate {
if supportedSSLSchemes.contains(url.scheme!) {
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,43 +350,24 @@ 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)
inStream.open()
outStream.open()
self.mutex.lock()
self.readyToWrite = true
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()
@@ -371,18 +377,20 @@ public class WebSocket : NSObject, StreamDelegate {
return // disconnectStream will be called.
}
}
guard !sOperation.isCancelled else { 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) {
open 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 trust = aStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust
let domain = aStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String
if sec.isValid(trust as! SecTrust, domain: domain) {
if sec.isValid(trust, domain: domain) {
certValidated = true
} else {
let error = errorWithDetail("Invalid SSL certificate", code: 1)
@@ -400,20 +408,23 @@ public class WebSocket : NSObject, StreamDelegate {
disconnectStream(nil)
}
}
/**
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)
}
}
/**
cleanup the streams.
*/
@@ -430,8 +441,9 @@ public class WebSocket : NSObject, StreamDelegate {
}
outputStream = nil
inputStream = nil
fragBuffer = nil
}
/**
Handles the incoming bytes and sending them to the proper processing method.
*/
@@ -439,7 +451,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 {
@@ -450,31 +461,33 @@ public class WebSocket : NSObject, StreamDelegate {
dequeueInput()
}
}
/**
Dequeue the incoming input so it is processed in order.
*/
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 }
}
}
/**
Handle checking the inital connection status
*/
@@ -482,22 +495,15 @@ 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
break // do nothing, we are going to collect more data
default:
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
}
}
/**
Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
*/
@@ -521,6 +527,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 {
@@ -530,7 +547,7 @@ public class WebSocket : NSObject, StreamDelegate {
}
return -1 // Was unable to find the full TCP header.
}
/**
Validates the HTTP is a 101 as per the RFC spec.
*/
@@ -551,14 +568,14 @@ public class WebSocket : NSObject, StreamDelegate {
}
return -1
}
/**
Read a 16 bit big endian value from a buffer
*/
private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
}
/**
Read a 64 bit big endian value from a buffer
*/
@@ -569,7 +586,7 @@ public class WebSocket : NSObject, StreamDelegate {
}
return value
}
/**
Write a 16-bit big endian value to a buffer.
*/
@@ -577,7 +594,7 @@ public class WebSocket : NSObject, StreamDelegate {
buffer[offset + 0] = UInt8(value >> 8)
buffer[offset + 1] = UInt8(value & 0xff)
}
/**
Write a 64-bit big endian value to a buffer.
*/
@@ -586,7 +603,7 @@ public class WebSocket : NSObject, StreamDelegate {
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
}
}
/**
Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process.
*/
@@ -624,10 +641,10 @@ public class WebSocket : NSObject, StreamDelegate {
let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping)
if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame &&
receivedOpcode != .textFrame && receivedOpcode != .pong) {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
writeError(errCode)
return emptyBuffer
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
writeError(errCode)
return emptyBuffer
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.protocolError.rawValue
@@ -635,34 +652,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
}
@@ -687,8 +692,24 @@ public class WebSocket : NSObject, StreamDelegate {
len = 0
data = Data()
} else {
if receivedOpcode == .connectionClose && len > 0 {
let size = MemoryLayout<UInt16>.size
offset += size
len -= UInt64(size)
}
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 {
callbackQueue.async { [weak self] in
@@ -715,7 +736,7 @@ public class WebSocket : NSObject, StreamDelegate {
if receivedOpcode == .continueFrame {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("first frame can't be a continue frame",
code: errCode))
code: errCode))
writeError(errCode)
return emptyBuffer
}
@@ -730,7 +751,7 @@ public class WebSocket : NSObject, StreamDelegate {
} else {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame",
code: errCode))
code: errCode))
writeError(errCode)
return emptyBuffer
}
@@ -745,12 +766,12 @@ public class WebSocket : NSObject, StreamDelegate {
}
_ = processResponse(response)
}
let step = Int(offset + numericCast(len))
return buffer.fromOffset(step)
}
}
/**
Process all messages in the buffer if possible.
*/
@@ -763,7 +784,7 @@ public class WebSocket : NSObject, StreamDelegate {
fragBuffer = Data(buffer: buffer)
}
}
/**
Process the finished response of a buffer.
*/
@@ -800,7 +821,7 @@ public class WebSocket : NSObject, StreamDelegate {
}
return false
}
/**
Create an error
*/
@@ -809,7 +830,7 @@ public class WebSocket : NSObject, StreamDelegate {
details[NSLocalizedDescriptionKey] = detail
return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details)
}
/**
Write an error to the socket
*/
@@ -819,14 +840,16 @@ public class WebSocket : NSObject, StreamDelegate {
WebSocket.writeUint16(buffer, offset: 0, value: code)
dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose)
}
/**
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)
@@ -847,13 +870,13 @@ public class WebSocket : NSObject, StreamDelegate {
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
_ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey)
offset += MemoryLayout<UInt32>.size
for i in 0..<dataLength {
buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size]
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)
@@ -876,20 +899,21 @@ public class WebSocket : NSObject, StreamDelegate {
callback()
}
}
break
}
}
}
writeQueue.addOperation(operation)
}
/**
Used to preform the disconnect delegate
*/
private func doDisconnect(_ error: NSError?) {
guard !didDisconnect else { return }
didDisconnect = true
isConnecting = false
connected = false
guard canDispatch else {return}
callbackQueue.async { [weak self] in
@@ -900,32 +924,31 @@ public class WebSocket : NSObject, StreamDelegate {
s.notificationCenter.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo)
}
}
// MARK: - Deinit
deinit {
mutex.lock()
readyToWrite = false
mutex.unlock()
cleanupStream()
}
}
private extension Data {
init(buffer: UnsafeBufferPointer<UInt8>) {
self.init(bytes: buffer.baseAddress!, count: buffer.count)
}
}
private extension UnsafeBufferPointer {
func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> {
return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset)
}
}
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)