为什么用URLSessionStreamTask写出时间?

时间:2017-08-28 05:34:52

标签: macos cocoa nsurlprotocol nsurlsessiontask

我正在练习制作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?

2 个答案:

答案 0 :(得分:1)

看起来你在一个while循环中排队了一大堆读取回调并且阻止了回调实际运行的线程永远不会从while循环返回。

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

你几乎不应该在任何类型的循环中调用异步方法。代替:

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

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

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

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

答案 1 :(得分:0)

我正打算在另一个论坛上提问。在我的步骤中,我提到我发出了请求行......

行?有...结局?

[查看RFC 1436,第2节]

哦,我计算并从URL发送检索字符串,但我忘了使用CR-LF来限制请求。这得到了请求。

但是现在我在回读时得到了超时......