Android项目中使用Ktor Client持续获取服务端数据直至断开连接
使用Ktor Client在Android中实现SSE持续数据接收
你的Node.js服务端实现的是Server-Sent Events (SSE) 协议,这是一种基于HTTP的单向推送技术,适合服务端持续向客户端发送数据。下面是Android端用Ktor Client对接的具体方案:
第一步:修正服务端的SSE格式问题
你的Node.js代码里res.write({data: count})不符合SSE规范,SSE要求每条消息必须以data: 开头,结尾用两个换行符\n\n,否则客户端无法正确解析。修改后的服务端代码:
const app = require("express")() let count = 0 app.get("/", (req, res) => { const headers = { 'Content-Type': 'text/event-stream', 'Connection': 'keep-alive', 'Cache-Control': 'no-cache' } res.writeHead(200, headers) setInterval(() => { // 遵循SSE格式:data: 内容\n\n res.write(`data: ${count}\n\n`) count++ }, 2000); }) app.listen(3000, () => console.log("ok"))
第二步:Android端添加Ktor依赖
在项目的build.gradle.kts(Module级别)中添加Ktor Client的核心和SSE相关依赖:
dependencies { // Ktor Client核心 implementation("io.ktor:ktor-client-core:2.3.10") // Android平台适配 implementation("io.ktor:ktor-client-android:2.3.10") // SSE支持 implementation("io.ktor:ktor-client-sse:2.3.10") // 协程依赖(Ktor基于协程) implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3") }
注意:版本号可以根据Ktor的最新稳定版调整。
第三步:实现Ktor Client的SSE接收逻辑
在Android的Activity或ViewModel中,使用协程发起SSE请求并持续接收数据:
import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import io.ktor.client.HttpClient import io.ktor.client.engine.android.Android import io.ktor.client.plugins.sse.sse import io.ktor.client.request.get import io.ktor.client.request.url import io.ktor.sse.SSEEvent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { // 创建带SSE支持的HttpClient private val client = HttpClient(Android) { install(io.ktor.client.plugins.sse.SSE) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // 启动协程接收SSE数据 CoroutineScope(Dispatchers.IO).launch { try { client.sse { // 连接到服务端SSE端点(替换为你的服务端IP/域名) get("http://192.168.1.100:3000/") { url("http://192.168.1.100:3000/") } // 持续接收事件 for (event in incoming) { when (event) { is SSEEvent.Data -> { // 获取服务端发送的数据,切换到主线程更新UI val data = event.data CoroutineScope(Dispatchers.Main).launch { // 这里处理数据,比如更新TextView // textView.text = "Received: $data" } } else -> {} // 处理其他类型的SSE事件(如注释、事件ID等) } } } } catch (e: Exception) { // 处理连接异常或断开的情况 e.printStackTrace() } finally { // 关闭客户端 client.close() } } } override fun onDestroy() { super.onDestroy() // 销毁时关闭客户端,断开连接 CoroutineScope(Dispatchers.IO).launch { client.close() } } }
关键说明
- Ktor的
SSE插件专门用于处理Server-Sent Events,自动维护长连接并解析符合规范的SSE消息。 - 必须使用协程执行网络请求,避免阻塞主线程。
- 服务端的IP地址需要替换为你的实际服务端地址(如果是本地测试,确保Android设备和Node.js服务在同一局域网)。
- 记得在AndroidManifest.xml中添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />
内容的提问来源于stack exchange,提问作者kallis
相关产品推荐
相关产品推荐

