SSE 的跨平台实现?

解读

国内面试官问“SSE 的跨平台实现”,并不是想听 HTTP/1.1 协议原文,而是考察候选人能否在 Kotlin 多平台(KMP)体系里,把“服务端推送”这条能力线从 JVM 到 Android、iOS、前端(JS/WASM)甚至桌面 Native 一路打通,同时兼顾国内网络环境(弱网、域名备案、HTTPS 强制、运营商缓存、Proxy 断开)与机型差异(华为无 GMS、iOS 低电量模式)。一句话:用 Kotlin 写一次 SSE 逻辑,各端都能“长连”收消息,且不掉线、不耗电、不违反商店政策。

知识点

  1. SSE 协议细节:text/event-stream 格式、id/event/data/retry 字段、Last-Event-ID、Content-Encoding: gzip、204 静默重试。
  2. Kotlin 多平台分层:commonMain 里声明 expect 接口,platformMain 提供 actual 实现;协程的 CommonFlow 作为统一回调。
  3. 各端事实上的最佳引擎:
    • JVM/Android:OkHttp 4.x 的 EventSource 实现,内置重连、拦截器、HTTP/2 多路复用。
    • iOS:NSURLSession 的 dataTask 挂起后逐行读取,配合 Kotlin-Native 的 Darwin 协程调度器;需手动处理 HTTP 代理、蜂窝/Wi-Fi 切换。
    • JS:浏览器原生 EventSource,但国内必须解决“HTTPS 混合内容”与“小程序 Web-view 白名单”;可降级到 fetch + ReadableStream 的 polyfill。
    • Native/Linux:libcurl 的 CURLOPT_READFUNCTION 回调,用 cinterop 封装成 Flow。
  4. 弱网容错:指数退避 + 最大重试上限;收到 id 字段后持久化到 commonMain 的 expect 存储接口,重启后带 Last-Event-ID 断点续传。
  5. 电量与政策:Android 端使用 WorkManager 做低优先级监听,iOS 端禁止后台常驻,退到 APNS 通道;前端页面可见时切 SSE,隐藏时切 WebSocket 或轮询。
  6. 二进制与编码:仅允许 UTF-8;国内部分网关会强制 gzip,解压逻辑放在平台层,common 层收纯文本。
  7. 安全:必须 WSS 或 HTTPS;证书需通过国内 CA 签发;Token 放在 Cookie 或 Authorization header,common 层统一签名接口。

答案

commonMain 里先定义一套与平台无关的接口:

expect interface SseEvent {
    val id: String?
    val event: String?
    val data: String
}

expect interface SseClient {
    fun connect(url: String, headers: Map<String, String> = emptyMap()): Flow<SseEvent>
    fun close()
}

在 JVM/Android 的 actual 实现中,用 OkHttp 的 EventSource 封装成 Flow:

actual class SseClient actual constructor() : Closeable {
    private val ok = OkHttpClient.Builder()
        .pingInterval(30, TimeUnit.SECONDS) // 防止运营商 NAT 超时
        .build()
    private var es: EventSource? = null

    actual fun connect(url: String, headers: Map<String, String>): Flow<SseEvent> =
        callbackFlow {
            val request = Request.Builder()
                .url(url)
                .apply { headers.forEach { (k, v) -> addHeader(k, v) } }
                .build()
            val listener = object : EventSourceListener() {
                override fun onOpen(eventSource: EventSource, response: Response) {}
                override fun onEvent(
                    eventSource: EventSource,
                    id: String?,
                    type: String?,
                    data: String
                ) {
                    trySend(object : SseEvent {
                        override val id = id
                        override val event = type
                        override val data = data
                    })
                }
                override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
                    cancel(CancellationException("SSE failure", t))
                }
                override fun onClosed(eventSource: EventSource) {
                    close()
                }
            }
            es = EventSource.Factory.create(listener, request).also { it.connect() }
            awaitClose { es?.cancel() }
        }.buffer(Channel.UNLIMITED).shareIn(GlobalScope, SharingStarted.WhileSubscribed())

    actual override fun close() = es?.cancel()
}

iOS actual 用 NSURLSession 的 dataTask 挂起后逐行读取,通过 Kotlin-Native 的 newSingleThreadContext 把回调转到协程:

actual class SseClient : Closeable {
    private val session = NSURLSession.sessionWithConfiguration(
        NSURLSessionConfiguration.defaultSessionConfiguration,
        delegateQueue = NSOperationQueue.mainQueue()
    )
    private var task: NSURLSessionDataTask? = null
    private val channel = Channel<SseEvent>(UNLIMITED)

    actual fun connect(url: String, headers: Map<String, String>): Flow<SseEvent> =
        flow {
            val req = NSMutableURLRequest.requestWithURL(NSURL(string = url))
            headers.forEach { (k, v) -> req.addValue(v, k) }
            task = session.dataTaskWithRequest(req) { data, _, error ->
                error?.let { channel.close(it) } ?: data?.let { d ->
                    d.toUtf8().lineSequence().forEach { line ->
                        parseLine(line)?.let { channel.trySend(it) }
                    }
                }
            }
            task?.resume()
            emitAll(channel.consumeAsFlow())
        }.flowOn(Dispatchers.Default)

    private fun parseLine(line: String): SseEvent? { ... }

    actual override fun close() {
        task?.cancel()
        session.invalidateAndCancel()
        channel.close()
    }
}

JS actual 直接包装浏览器 EventSource,并做 HTTPS 检测:

actual class SseClient {
    private var es: EventSource? = null
    actual fun connect(url: String, headers: Map<String, String>): Flow<SseEvent> =
        callbackFlow {
            if (window.location.protocol == "https:" && url.startsWith("http:")) {
                throw IllegalArgumentException("Mixed content blocked in China")
            }
            val es = EventSource(url)
            headers.forEach { (k, v) -> es.setRequestHeader(k, v) } // 部分浏览器不支持,需回退 fetch
            es.onmessage = { trySend(JsSseEvent(it)) }
            es.onerror = { close() }
            awaitClose { es.close() }
        }

    actual fun close() = es?.close()
}

最后在国内上线时,把域名接入 CDN 并开启 HTTPS,配置 retry: 3000 与 gzip,移动端配合 WorkManager/APNS 做后台降级,即可达到“一套 Kotlin 代码,五端同时收 SSE”的跨平台目标。

拓展思考

  1. 如果业务需要双向通信,SSE 只能服务端→客户端,此时可让客户端通过 HTTP/2 的 gRPC-Web 或 WebSocket 发送上行数据,而下行仍用 SSE 做广播,实现“混合通道”。
  2. 国内小程序环境禁止 EventSource,可用 wx.request 的 streaming 模式模拟,或直接用 WebSocket;思考如何用 Kotlin/JS 的 expect/actual 把小程序 API 也封装进同一套 Flow。
  3. 当用户量达到百万级,单台 NGINX 撑不住长连,可考虑用 EMQX 或 Pulsar 的 SSE proxy,边缘节点只保持 TCP 连接,后端通过 MQ 广播;此时 Kotlin 侧只需切换域名,无需改代码。
  4. 在 Kotlin/Native 的桌面端,若目标平台是 Windows 7,需要把 TLS 1.2 补丁和根证书更新也打包进安装器,否则 SSE 握手会失败;思考如何用 gradle-plugin 自动检测系统版本并提示用户。