Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Network connection socket #352

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
language: swift
osx_image: xcode11.1
osx_image: xcode12.2

before_install:
- wget https://www.emqx.io/downloads/broker/v3.2.7/emqx-macosx-v3.2.7.zip -O emqx.zip
- unzip emqx.zip
- brew install openssl
- echo "limit maxfiles 65535 unlimited" | sudo tee -a /etc/launchd.conf
- emqx/bin/emqx start
- git clone https://github.com/hjianbo/xcode-coveralls --depth=1
- cd xcode-coveralls && git submodule init && git submodule update && cd ..
Expand Down
13 changes: 11 additions & 2 deletions CocoaMQTT.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,22 @@ Pod::Spec.new do |s|
s.tvos.deployment_target = "10.0"
# s.watchos.deployment_target = "2.0"
s.source = { :git => "https://github.com/emqx/CocoaMQTT.git", :tag => "1.3.0-rc.1"}
s.default_subspec = 'Core'
s.default_subspecs = ['Core', 'CocoaAsyncSocket']

s.subspec 'Core' do |ss|
ss.dependency "CocoaAsyncSocket", "~> 7.6.3"
ss.source_files = "Source/*.swift"
ss.exclude_files = "Source/CocoaMQTTWebSocket.swift"
end

s.subspec 'Network' do |ss|
ss.dependency "CocoaMQTT/Core"
ss.framework = "Network"
end

s.subspec 'CocoaAsyncSocket' do |ss|
ss.dependency "CocoaMQTT/Core"
ss.dependency "CocoaAsyncSocket", "~> 7.6.3"
end

s.subspec 'WebSockets' do |ss|
ss.dependency "CocoaMQTT/Core"
Expand Down
4 changes: 4 additions & 0 deletions CocoaMQTT.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
8D43DE6622FAFF2500D9A06B /* FrameDisconnect.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D43DE6522FAFF2500D9A06B /* FrameDisconnect.swift */; };
8D7A262E23AF2FEA00CE7442 /* client-keycert.p12 in Resources */ = {isa = PBXBuildFile; fileRef = 8D7A262D23AF2FEA00CE7442 /* client-keycert.p12 */; };
8D7A262F23AF3B4700CE7442 /* Starscream.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6EC871DF23A4214000F69AE8 /* Starscream.framework */; };
8E67B6C12533F70B00B2468E /* CocoaMQTTNetworkConnectionSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E67B6C02533F70B00B2468E /* CocoaMQTTNetworkConnectionSocket.swift */; };
/* End PBXBuildFile section */

/* Begin PBXContainerItemProxy section */
Expand Down Expand Up @@ -106,6 +107,7 @@
8D43DE6322FAFE5F00D9A06B /* FramePingResp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FramePingResp.swift; sourceTree = "<group>"; };
8D43DE6522FAFF2500D9A06B /* FrameDisconnect.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FrameDisconnect.swift; sourceTree = "<group>"; };
8D7A262D23AF2FEA00CE7442 /* client-keycert.p12 */ = {isa = PBXFileReference; lastKnownFileType = file; path = "client-keycert.p12"; sourceTree = "<group>"; };
8E67B6C02533F70B00B2468E /* CocoaMQTTNetworkConnectionSocket.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CocoaMQTTNetworkConnectionSocket.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -187,6 +189,7 @@
6EC871E123A4214D00F69AE8 /* Socket */ = {
isa = PBXGroup;
children = (
8E67B6C02533F70B00B2468E /* CocoaMQTTNetworkConnectionSocket.swift */,
6EC871E223A421A200F69AE8 /* CocoaMQTTSocket.swift */,
6EC871E423A421DE00F69AE8 /* CocoaMQTTWebSocket.swift */,
);
Expand Down Expand Up @@ -410,6 +413,7 @@
8D43DE5622FAEDDA00D9A06B /* FramePubComp.swift in Sources */,
82519C0722ACC6E100FA0815 /* CocoaMQTTTypes.swift in Sources */,
8D43DE4C22FAEB8B00D9A06B /* FrameConnect.swift in Sources */,
8E67B6C12533F70B00B2468E /* CocoaMQTTNetworkConnectionSocket.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>classNames</key>
<dict>
<key>CocoaMQTTDeliverTests</key>
<dict>
<key>testPeformance()</key>
<dict>
<key>com.apple.XCTPerformanceMetric_WallClockTime</key>
<dict>
<key>baselineAverage</key>
<real>0.53048</real>
<key>baselineIntegrationDisplayName</key>
<string>Local Baseline</string>
</dict>
</dict>
</dict>
</dict>
</dict>
</plist>
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>runDestinationsByUUID</key>
<dict>
<key>FC308DFA-46BF-4819-BFFC-8CA38FDABFE7</key>
<dict>
<key>localComputer</key>
<dict>
<key>busSpeedInMHz</key>
<integer>400</integer>
<key>cpuCount</key>
<integer>1</integer>
<key>cpuKind</key>
<string>8-Core Intel Core i9</string>
<key>cpuSpeedInMHz</key>
<integer>2300</integer>
<key>logicalCPUCoresPerPackage</key>
<integer>16</integer>
<key>modelCode</key>
<string>MacBookPro16,1</string>
<key>physicalCPUCoresPerPackage</key>
<integer>8</integer>
<key>platformIdentifier</key>
<string>com.apple.platform.macosx</string>
</dict>
<key>targetArchitecture</key>
<string>x86_64</string>
</dict>
</dict>
</dict>
</plist>
6 changes: 6 additions & 0 deletions CocoaMQTTTests/CocoaMQTTDeliverTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,12 @@ class CocoaMQTTDeliverTests: XCTestCase {
ms_sleep(100)
XCTAssertEqual(storage.readAll().count, 0)
}

func testPeformance() {
measure {
testStorage()
}
}

func testTODO() {
// TODO: How to test large of messages combined qos0/qos1/qos2
Expand Down
2 changes: 2 additions & 0 deletions Example/Podfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@ platform :ios, 10.0
use_frameworks!

target 'Example' do
pod 'CocoaMQTT', :path => '../'
pod 'CocoaMQTT/WebSockets', :path => '../'
pod 'CocoaMQTT/CocoaAsyncSocket', :path => '../'
end
21 changes: 12 additions & 9 deletions Source/CocoaMQTT.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
//

import Foundation
import CocoaAsyncSocket

/**
* Connection State
Expand Down Expand Up @@ -164,8 +163,18 @@ public class CocoaMQTT: NSObject, CocoaMQTTClient {
///
/// - Note:
public var backgroundOnSocket: Bool {
get { return (self.socket as? CocoaMQTTSocket)?.backgroundOnSocket ?? true }
set { (self.socket as? CocoaMQTTSocket)?.backgroundOnSocket = newValue }
get {
#if canImport(CocoaAsyncSocket)
return (self.socket as? CocoaMQTTSocket)?.backgroundOnSocket ?? true
#else
return true
#endif
}
set {
#if canImport(CocoaAsyncSocket)
(self.socket as? CocoaMQTTSocket)?.backgroundOnSocket = newValue
#endif
}
}

/// Delegate Executed queue. Default is `DispatchQueue.main`
Expand Down Expand Up @@ -559,12 +568,6 @@ extension CocoaMQTT: CocoaMQTTSocketDelegate {
didReceiveTrust(self, trust, completionHandler)
}

// ?
public func socketDidSecure(_ sock: GCDAsyncSocket) {
printDebug("Socket has successfully completed SSL/TLS negotiation")
sendConnectFrame()
}

public func socket(_ socket: CocoaMQTTSocketProtocol, didWriteDataWithTag tag: Int) {
// XXX: How to print writed bytes??
}
Expand Down
4 changes: 2 additions & 2 deletions Source/CocoaMQTTDeliver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ class CocoaMQTTDeliver: NSObject {
var isInflightFull: Bool { get { return inflight.count >= inflightWindowSize }}
var isInflightEmpty: Bool { get { return inflight.count == 0 }}

var storage: CocoaMQTTStorage?
var storage: CocoaMQTTStorageProtocol?

func recoverSessionBy(_ storage: CocoaMQTTStorage) {
func recoverSessionBy(_ storage: CocoaMQTTStorageProtocol) {

let frames = storage.takeAll()
guard frames.count >= 0 else {
Expand Down
110 changes: 110 additions & 0 deletions Source/CocoaMQTTNetworkConnectionSocket.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
//
// CocoaMQTTNetworkConnectionSocket.swift
// CocoaMQTT
//
// Created by Arthur Kao on 2020/10/12.
// Copyright © 2020 emqx.io. All rights reserved.
//

#if canImport(Network)
import Foundation
import Network

// MARK: - CocoaMQTTNetworkConnectionSocket

@available(OSX 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
public class CocoaMQTTNetworkConnectionSocket: NSObject {

public var enableSSL = false

///
public var sslSettings: [String: NSObject]?

/// Allow self-signed ca certificate.
///
/// Default is false
public var allowUntrustCACertificate = false

fileprivate var reference: NWConnection?
fileprivate weak var delegate: CocoaMQTTSocketDelegate?
fileprivate var delegateQueue: DispatchQueue?

public override init() { super.init() }
}

@available(OSX 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
extension CocoaMQTTNetworkConnectionSocket: CocoaMQTTSocketProtocol {
public func setDelegate(_ theDelegate: CocoaMQTTSocketDelegate?, delegateQueue: DispatchQueue?) {
delegate = theDelegate
self.delegateQueue = delegateQueue
}

public func connect(toHost host: String, onPort port: UInt16) throws {
try connect(toHost: host, onPort: port, withTimeout: -1)
}

public func connect(toHost host: String, onPort port: UInt16, withTimeout timeout: TimeInterval) throws {
let reference = NWConnection(host: NWEndpoint.Host(host), port: NWEndpoint.Port(rawValue: port)!, using: enableSSL ? createTLSParameters(allowInsecure: allowUntrustCACertificate, queue: delegateQueue ?? .main) : .tcp)
self.reference = reference
reference.stateUpdateHandler = { state in
switch state {
case .ready:
self.delegate?.socketConnected(self)
case .failed(let error):
self.delegate?.socketDidDisconnect(self, withError: error)
case .cancelled:
self.delegate?.socketDidDisconnect(self, withError: nil)
default:
break
}
}
reference.start(queue: delegateQueue ?? .main)
}

public func disconnect() {
reference?.cancel()
}

public func readData(toLength length: UInt, withTimeout timeout: TimeInterval, tag: Int) {
reference?.receive(minimumIncompleteLength: Int(length), maximumLength: Int(length)) { (data, ctx, b, errpr) in
guard let data = data else { return }
self.delegate?.socket(self, didRead: data, withTag: tag)
}
}

public func write(_ data: Data, withTimeout timeout: TimeInterval, tag: Int) {
let completion = NWConnection.SendCompletion.contentProcessed { (error) in
if let error = error {
self.delegate?.socketDidDisconnect(self, withError: error)
} else {
self.delegate?.socket(self, didWriteDataWithTag: tag)
}
}
reference?.send(content: data, completion: completion)
}
}

@available(OSX 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
extension CocoaMQTTNetworkConnectionSocket {
func createTLSParameters(allowInsecure: Bool, queue: DispatchQueue) -> NWParameters {
let options = NWProtocolTLS.Options()
if allowInsecure {
sec_protocol_options_set_verify_block(options.securityProtocolOptions, { (sec_protocol_metadata, sec_trust, sec_protocol_verify_complete) in
let trust = sec_trust_copy_ref(sec_trust).takeRetainedValue()
var error: CFError?
if SecTrustEvaluateWithError(trust, &error) {
sec_protocol_verify_complete(true)
} else {
self.delegate?.socket(self, didReceive: trust, completionHandler: sec_protocol_verify_complete)
}
}, queue)
}
if let certificates = sslSettings?[(kCFStreamSSLCertificates as String)] as? NSArray {
certificates.compactMap { sec_identity_create($0 as! SecIdentity) }.forEach { secIdentity in
sec_protocol_options_set_local_identity(options.securityProtocolOptions, secIdentity)
}
}
return NWParameters(tls: options)
}
}
#endif
6 changes: 6 additions & 0 deletions Source/CocoaMQTTSocket.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
//

import Foundation
#if canImport(CocoaAsyncSocket)
import CocoaAsyncSocket
#endif

// MARK: - Interfaces

Expand All @@ -30,6 +32,7 @@ public protocol CocoaMQTTSocketProtocol {
func write(_ data: Data, withTimeout timeout: TimeInterval, tag: Int)
}

#if canImport(CocoaAsyncSocket)
// MARK: - CocoaMQTTSocket

public class CocoaMQTTSocket: NSObject {
Expand Down Expand Up @@ -133,3 +136,6 @@ extension CocoaMQTTSocket: GCDAsyncSocketDelegate {
delegate?.socketDidDisconnect(self, withError: err)
}
}
#elseif canImport(Network)
public typealias CocoaMQTTSocket = CocoaMQTTNetworkConnectionSocket
#endif
Loading