Skip to content

Commit

Permalink
fix bug
Browse files Browse the repository at this point in the history
  • Loading branch information
huiping192 committed May 4, 2024
1 parent 97dfe34 commit 8d63f2a
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions Sources/HPRTMP/Network/NetworkClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ final class RTMPClientHandler: ChannelInboundHandler {

func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let data = self.unwrapInboundIn(data)
guard !data.isEmpty else { return }
responseCallback(data)
}
}
Expand Down Expand Up @@ -52,6 +53,7 @@ class NetworkClient: NetworkConnectable {
private var host: String?
private var port: Int?

private var cachedReceivedData: Data = .init()
private var dataPromise: EventLoopPromise<Data>?

init() {
Expand Down Expand Up @@ -89,15 +91,27 @@ class NetworkClient: NetworkConnectable {
}

func receiveData() async throws -> Data {
guard let promise = self.dataPromise else {
throw NSError(domain: "RTMPClientError", code: 2, userInfo: [NSLocalizedDescriptionKey: "Data promise is not initialized."])
guard let channel = self.channel else {
print("Connection not established")
throw NSError(domain: "RTMPClientError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Connection not established"])
}
self.dataPromise = channel!.eventLoop.makePromise(of: Data.self)
return try await promise.futureResult.get()
if !cachedReceivedData.isEmpty {
let data = cachedReceivedData
cachedReceivedData = Data()
return data
}

self.dataPromise = channel.eventLoop.makePromise(of: Data.self)
return try await dataPromise!.futureResult.get()
}

private func responseReceived(data: Data) {
self.dataPromise?.succeed(data)
cachedReceivedData.append(data)
if let dataPromise {
dataPromise.succeed(cachedReceivedData)
cachedReceivedData = Data()
self.dataPromise = nil
}
}

func shutdown() {
Expand Down

0 comments on commit 8d63f2a

Please sign in to comment.