From 170d5e6fc1814b2a6f95754c099aeffbb346327b Mon Sep 17 00:00:00 2001 From: Huiping Guo Date: Thu, 7 Sep 2023 22:16:22 +0900 Subject: [PATCH] extract network part to protcol --- Sources/HPRTMP/Network.swift | 43 ++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Sources/HPRTMP/Network.swift diff --git a/Sources/HPRTMP/Network.swift b/Sources/HPRTMP/Network.swift new file mode 100644 index 0000000..2895733 --- /dev/null +++ b/Sources/HPRTMP/Network.swift @@ -0,0 +1,43 @@ + + +import Foundation +import Network + +protocol RTMPConnectable { + func connect(host: String, port: UInt16) async throws + func sendData(_ data: Data) async throws + func receiveData() async throws -> Data +} + +actor NWConnecter: RTMPConnectable { + private var connection: NWConnection? + + public func connect(host: String, port: UInt16) async throws { + let connection = NWConnection(host: NWEndpoint.Host(host), port: NWEndpoint.Port(rawValue: port) ?? 1935, using: .tcp) + self.connection = connection + connection.stateUpdateHandler = { [weak self] newState in + guard let self else { return } + Task { + switch newState { + case .ready: + break + case .failed(let error): + break + default: + break + } + } + } +// NWConnection.maxReadSize = Int((await windowControl.windowSize)) + connection.start(queue: DispatchQueue.global(qos: .default)) + } + + func sendData(_ data: Data) async throws { + try await connection?.sendData(data) + } + + func receiveData() async throws -> Data { + guard let connection = self.connection else { return Data() } + return try await connection.receiveData() + } +}