Ktor Client 中的 WebSockets
所需依赖项:io.ktor:ktor-client-websockets
代码示例: client-websockets
客户端的 WebSockets 插件允许您处理 WebSocket 会话以与服务器交换消息。
并非所有引擎都支持 WebSocket。有关受支持引擎的概览,请参阅限制。
要了解服务器端对 WebSocket 的支持,请参阅 Ktor Server 中的 WebSocketsWebSockets 插件允许你在服务器与客户端之间创建多路通信会话。。
添加依赖项
要使用 WebSockets,您需要在构建脚本中包含 ktor-client-websockets 工件:
implementation(ktorLibs.client.websockets)implementation ktorLibs.client.websockets<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-client-websockets-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>安装 WebSockets
要安装 WebSockets 插件,请在客户端配置块内将其传递给 install 函数:
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.websocket.*
//...
val client = HttpClient(CIO) {
install(WebSockets)
}配置
(可选)您可以通过传递 WebSockets.Config 支持的属性,在 install 块内配置该插件。
maxFrameSizeFrame 大小。 contentConverterpingIntervalMillisLong 格式指定 ping 之间的时间间隔。 pingIntervalDuration 格式指定 ping 之间的时间间隔。 pingInterval 和 pingIntervalMillis 属性不适用于 OkHttp 引擎。要为 OkHttp 设置 ping 间隔,可以使用引擎配置:
import io.ktor.client.engine.okhttp.OkHttp
val client = HttpClient(OkHttp) {
engine {
preconfigured = OkHttpClient.Builder()
.pingInterval(20, TimeUnit.SECONDS)
.build()
}
} 在以下示例中,WebSockets 插件配置了 20 秒(20_000 毫秒)的 ping 间隔,以自动发送 ping 帧并保持 WebSocket 连接处于活动状态:
val client = HttpClient(CIO) {
install(WebSockets) {
pingIntervalMillis = 20_000
}
}使用 WebSocket 会话
客户端的 WebSocket 会话由 DefaultClientWebSocketSession 接口表示。该接口公开了允许您发送和接收 WebSocket 帧以及关闭会话的 API。
访问 WebSocket 会话
HttpClient 提供了两种访问 WebSocket 会话的主要方式:
webSocket() 函数接受
DefaultClientWebSocketSession作为块实参。kotlinrunBlocking { client.webSocket( method = HttpMethod.Get, host = "127.0.0.1", port = 8080, path = "/echo" ) { // this: DefaultClientWebSocketSession } }- webSocketSession() 函数返回
DefaultClientWebSocketSession实例,并允许您在runBlocking或launch作用域之外访问会话。
处理 WebSocket 会话
在函数块内,您可以为指定路径定义处理程序。以下函数和属性可在该块内使用:
send()send() 函数向服务器发送文本内容。 outgoingoutgoing 属性访问用于发送 WebSocket 帧的通道。帧由 Frame 类表示。 incomingincoming 属性访问用于接收 WebSocket 帧的通道。帧由 Frame 类表示。 close()close() 函数发送带有指定原因的关闭帧。 帧类型
您可以检查 WebSocket 帧的类型并进行相应处理。一些常见的帧类型包括:
Frame.Text表示文本帧。使用Frame.Text.readText()读取其内容。Frame.Binary表示二进制帧。使用Frame.Binary.readBytes()读取其内容。Frame.Close表示关闭帧。使用Frame.Close.readReason()获取会话关闭的原因。
示例
以下示例创建了 echo WebSocket 端点,并展示了如何向服务器发送和接收消息。
package com.example
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.websocket.*
import io.ktor.http.*
import io.ktor.websocket.*
import kotlinx.coroutines.*
import java.util.*
fun main() {
val client = HttpClient(CIO) {
install(WebSockets) {
pingIntervalMillis = 20_000
}
}
runBlocking {
client.webSocket(method = HttpMethod.Get, host = "127.0.0.1", port = 8080, path = "/echo") {
while(true) {
val othersMessage = incoming.receive() as? Frame.Text
println(othersMessage?.readText())
val myMessage = Scanner(System.`in`).next()
if(myMessage != null) {
send(myMessage)
}
}
}
}
client.close()
}有关完整示例,请参阅 client-websockets。
