gpt4 book ai didi

macos - 为什么使用 URLSessionStreamTask 写入会超时?

转载 作者:行者123 更新时间:2023-12-03 17:47:45 25 4
gpt4 key购买 nike

我正在练习创建一个 URLProtocol 子类。我正在使用 URLSessionStreamTask 进行读取和写入。当尝试子类时,我遇到了超时。我以为我搞乱了我的阅读例程,但添加日志记录表明我没有通过最初的写入!

这是我的子类的缩短版本:

import Foundation
import LoggerAPI

class GopherUrlProtocol: URLProtocol {

enum Constants {
static let schemeName = "gopher"
static let defaultPort = 70
}

var innerSession: URLSession?
var innerTask: URLSessionStreamTask?

override class func canInit(with request: URLRequest) -> Bool { /*...*/ }
override class func canonicalRequest(for request: URLRequest) -> URLRequest { /*...*/ }

override func startLoading() {
Log.entry("Starting up a download")
defer { Log.exit("Started a download") }

precondition(innerSession == nil)
precondition(innerTask == nil)

innerSession = URLSession(configuration: .ephemeral, delegate: self, delegateQueue: .current)
innerTask = innerSession?.streamTask(withHostName: (request.url?.host)!, port: request.url?.port ?? Constants.defaultPort)
innerTask!.resume()
downloadGopher()
}

override func stopLoading() {
Log.entry("Stopping a download")
defer { Log.exit("Stopped a download") }

innerTask?.cancel()
innerTask = nil
innerSession = nil
}

}

extension GopherUrlProtocol {

func downloadGopher() {
Log.entry("Doing a gopher download")
defer { Log.exit("Did a gopher download") }

guard let task = innerTask, let url = request.url, let path = URLComponents(url: url, resolvingAgainstBaseURL: false)?.path else { return }

let downloadAsText = determineTextDownload(path)
task.write(determineRetrievalKey(path).data(using: .isoLatin1)!, timeout: innerSession?.configuration.timeoutIntervalForRequest ?? 60) {
Log.entry("Responding to a write with error '\(String(describing: $0))'")
defer { Log.exit("Responded to a write") }
Log.info("Hi")

if let error = $0 {
self.client?.urlProtocol(self, didFailWithError: error)
return
}

var hasSentClientData = false
var endReadLoop = false
let aMinute: TimeInterval = 60
let bufferSize = 1024
let noData = Data()
var result = noData
while !endReadLoop {
task.readData(ofMinLength: 1, maxLength: bufferSize, timeout: self.innerSession?.configuration.timeoutIntervalForRequest ?? aMinute) { data, atEOF, error in
Log.entry("Responding to a read with data '\(String(describing: data))', at-EOF '\(atEOF)', and error '\(String(describing: error))'")
defer { Log.exit("Responded to a read") }
Log.info("Hello")

if let error = error {
self.client?.urlProtocol(self, didFailWithError: error)
endReadLoop = true
return
}
endReadLoop = atEOF
result.append(data ?? noData)
hasSentClientData = hasSentClientData || data != nil
}
}
if hasSentClientData {
self.client?.urlProtocol(self, didReceive: URLResponse(url: url, mimeType: downloadAsText ? "text/plain" : "application/octet-stream", expectedContentLength: result.count, textEncodingName: nil), cacheStoragePolicy: .notAllowed) // To-do: Update cache policy
self.client?.urlProtocol(self, didLoad: result)
}
}
}

}

extension GopherUrlProtocol: URLSessionStreamDelegate {}

和日志:

[2017-08-28T00:52:33.861-04:00] [ENTRY] [GopherUrlProtocol.swift:39 canInit(with:)] GopherUrlProtocol checks if it can 'init' gopher://gopher.floodgap.com/
[2017-08-28T00:52:33.863-04:00] [EXIT] [GopherUrlProtocol.swift:41 canInit(with:)] Returning true
[2017-08-28T00:52:33.863-04:00] [ENTRY] [GopherUrlProtocol.swift:39 canInit(with:)] GopherUrlProtocol checks if it can 'init' gopher://gopher.floodgap.com/
[2017-08-28T00:52:33.863-04:00] [EXIT] [GopherUrlProtocol.swift:41 canInit(with:)] Returning true
[2017-08-28T00:52:33.864-04:00] [ENTRY] [GopherUrlProtocol.swift:54 canonicalRequest(for:)] GopherUrlProtocol canonizes gopher://gopher.floodgap.com/
[2017-08-28T00:52:33.864-04:00] [EXIT] [GopherUrlProtocol.swift:56 canonicalRequest(for:)] Returning gopher://gopher.floodgap.com
[2017-08-28T00:52:33.867-04:00] [ENTRY] [GopherUrlProtocol.swift:82 startLoading()] Starting up a download
[2017-08-28T00:52:33.868-04:00] [ENTRY] [GopherUrlProtocol.swift:112 downloadGopher()] Doing a gopher download
[2017-08-28T00:52:33.868-04:00] [EXIT] [GopherUrlProtocol.swift:113 downloadGopher()] Did a gopher download
[2017-08-28T00:52:33.868-04:00] [EXIT] [GopherUrlProtocol.swift:83 startLoading()] Started a download
[2017-08-28T00:53:33.871-04:00] [ENTRY] [GopherUrlProtocol.swift:132 downloadGopher()] Responding to a write with error 'Optional(Error Domain=NSPOSIXErrorDomain Code=60 "Operation timed out" UserInfo={_kCFStreamErrorCodeKey=60, _kCFStreamErrorDomainKey=1})'
[2017-08-28T00:53:33.871-04:00] [INFO] [GopherUrlProtocol.swift:134 downloadGopher()] Hi
[2017-08-28T00:53:33.872-04:00] [EXIT] [GopherUrlProtocol.swift:133 downloadGopher()] Responded to a write
[2017-08-28T00:53:33.876-04:00] [ENTRY] [GopherUrlProtocol.swift:95 stopLoading()] Stopping a download
[2017-08-28T00:53:33.876-04:00] [ERROR] [main.swift:42 cget] Retrieval Error: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x100e01470 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=gopher://gopher.floodgap.com, NSErrorFailingURLKey=gopher://gopher.floodgap.com, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}
[2017-08-28T00:53:33.876-04:00] [EXIT] [GopherUrlProtocol.swift:96 stopLoading()] Stopped a download
Program ended with exit code: 11

奇怪的是,写闭包的日志记录仅有时出现。也许这是某种线程/计时问题。 (在这里,我运行了该程序两次。)

我使用的URLSessionStreamTask是否错误?或者 URLProtocol 错误?或者,虽然不是 HTTP,但我是否触发了 ATS?

最佳答案

看起来您在 while 循环中排队了疯狂数量的读取回调,并通过从不从 while 循环返回来阻塞实际运行回调的线程。

该读取调用是异步的,这意味着内部回调将稍后运行 - 可能很久稍后运行。因此,你的“while not EOF”会阻塞调用线程,确保它永远不会返回到运行循环的顶部以允许回调运行,从而确保回调永远无法设置 eof 标志来终止while 循环。本质上,您使线程陷入僵局。

您几乎不应该在任何类型的循环中调用异步方法。相反:

  • 创建一个方法,其唯一目的是返回该 block /闭包(可能是 getReadHandlerBlock)。
  • 调用 read 方法,并将调用返回的 block 传递给 getReadHandlerBlock

然后,读取处理程序 block 的底部:

  • 查看您是否需要阅读更多内容。
  • 如果是这样,请对 self 的弱引用调用 getReadHandlerBlock 以获取对读取处理程序 block 的引用。
  • 调用 read 方法。

希望有帮助。 (请注意,我并不是说这是代码的唯一问题;我没有详细研究它。这只是我注意到的第一件事。)

关于macos - 为什么使用 URLSessionStreamTask 写入会超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45912289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com