launchdarkly / swift-eventsource

Server-sent events (SSE) client implementation in Swift for iOS, macOS, tvOS, and watchOS
https://launchdarkly.github.io/swift-eventsource/
Other
187 stars 34 forks source link

一直重连,怎么中断? #82

Open yayongiOSer opened 1 month ago

yayongiOSer commented 1 month ago

`// Tells the delegate that the task finished transferring data. public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { utf8LineParser.closeAndReset() let currentRetry = eventParser.reset()

    guard readyState != .shutdown
    else { return }

    if let error = error {
        if (error as NSError).code != NSURLErrorCancelled {
            logger.log(.info, "Connection error: %@", error.localizedDescription)
            if dispatchError(error: error) == .shutdown {
                logger.log(.info, "Connection has been explicitly shut down by error handler")
                if readyState == .open {
                    config.handler.onClosed()
                }
                readyState = .shutdown
                return
            }
        }
    } else {
        logger.log(.info, "Connection unexpectedly closed.")
    }

    if readyState == .open {
        config.handler.onClosed()
    }

    readyState = .closed
    let sleep = reconnectionTimer.reconnectDelay(baseDelay: currentRetry)
    // this formatting shenanigans is to workaround String not implementing CVarArg on Swift<5.4 on Linux
    logger.log(.info, "Waiting %@ seconds before reconnecting...", String(format: "%.3f", sleep))
    delegateQueue.asyncAfter(deadline: .now() + sleep) { [weak self] in
        self?.connect()
    }
}`

这个方法在 readyState = .closed 之后,为什么有 sleep 后重新连接的逻辑,如何设置可以终止呢?

keelerm84 commented 1 month ago

My apologies for the delay in responding to your inquiry.

This library's primary motivation is to support LaunchDarkly SDKs. We need the SDKs to always be connected to the upstream data streams to ensure evaluations are up to date. So by default, when this library receives a disconnect, we want it to perform a reasonable backoff + jitter retry policy before continuing.

However, when instantiating this library, you can provide your own custom handler to the config. That handler has a method onClosed which you can use to then signal that the stream should be permanently shut down.