Skip to content

WebSocket

源:Ktor WebSocket | OkHttp WebSocket

WebSocket 提供全双工实时通信。本文展示如何使用 Ktor 实现跨平台 WebSocket 客户端。

标准代码块

kotlin
import io.ktor.client.*
import io.ktor.client.plugins.websocket.*
import io.ktor.websocket.*
import kotlinx.coroutines.flow.*

class WebSocketClient(private val client: HttpClient) {
    
    suspend fun connect(url: String): Flow<String> = flow {
        client.webSocket(url) {
            // 发送消息
            send("Hello Server")
            
            // 接收消息
            for (frame in incoming) {
                when (frame) {
                    is Frame.Text -> emit(frame.readText())
                    else -> {}
                }
            }
        }
    }
}

依赖补充

kotlin
kotlin {
    sourceSets {
        commonMain.dependencies {
            implementation("io.ktor:ktor-client-websockets:2.3.7")
        }
    }
}