Skip to content
Client Plugin

Ktor Client 中的 WebSockets

所需依赖项:io.ktor:ktor-client-websockets

代码示例: client-websockets

WebSocket 是一种在单个 TCP 连接上为用户浏览器和服务器之间提供全双工通信会话的协议。对于创建需要与服务器进行实时数据传输的应用程序,它尤为有用。 Ktor 在服务器端和客户端均支持 WebSocket 协议。

客户端的 WebSockets 插件允许您处理 WebSocket 会话以与服务器交换消息。

并非所有引擎都支持 WebSocket。有关受支持引擎的概览,请参阅限制。

要了解服务器端对 WebSocket 的支持,请参阅 Ktor Server 中的 WebSocketsWebSockets 插件允许你在服务器与客户端之间创建多路通信会话。。

添加依赖项

要使用 WebSockets,您需要在构建脚本中包含 ktor-client-websockets 工件:

kotlin
implementation(ktorLibs.client.websockets)
上述代码段使用 Ktor 版本目录来指定 Ktor 依赖项。
groovy
implementation ktorLibs.client.websockets
上述代码段使用 Ktor 版本目录来指定 Ktor 依赖项。
xml
<dependency>
    <groupId>io.ktor</groupId>
    <artifactId>ktor-client-websockets-jvm</artifactId>
    <version>${ktor_version}</version>
</dependency>
要详细了解 Ktor 客户端所需的工件,请参阅 添加客户端依赖项了解如何向现有项目添加客户端依赖项。。

安装 WebSockets

要安装 WebSockets 插件,请在客户端配置块内将其传递给 install 函数:

kotlin
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 块内配置该插件。

maxFrameSize
设置可接收或发送的最大 Frame 大小。
contentConverter
设置用于序列化/反序列化的转换器。
pingIntervalMillis
以 Long 格式指定 ping 之间的时间间隔。
pingInterval
以 Duration 格式指定 ping 之间的时间间隔。

pingInterval 和 pingIntervalMillis 属性不适用于 OkHttp 引擎。要为 OkHttp 设置 ping 间隔,可以使用引擎配置:

kotlin
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 连接处于活动状态:

kotlin
val client = HttpClient(CIO) {
    install(WebSockets) {
        pingIntervalMillis = 20_000
    }
}

使用 WebSocket 会话

客户端的 WebSocket 会话由 DefaultClientWebSocketSession 接口表示。该接口公开了允许您发送和接收 WebSocket 帧以及关闭会话的 API。

访问 WebSocket 会话

HttpClient 提供了两种访问 WebSocket 会话的主要方式:

  • webSocket() 函数接受 DefaultClientWebSocketSession 作为块实参。

    kotlin
    runBlocking {
        client.webSocket(
            method = HttpMethod.Get,
            host = "127.0.0.1",
            port = 8080,
            path = "/echo"
        ) {
            // this: DefaultClientWebSocketSession
        }
    }
  • webSocketSession() 函数返回 DefaultClientWebSocketSession 实例,并允许您在 runBlocking 或 launch 作用域之外访问会话。

处理 WebSocket 会话

在函数块内,您可以为指定路径定义处理程序。以下函数和属性可在该块内使用:

send()
使用 send() 函数向服务器发送文本内容。
outgoing
使用 outgoing 属性访问用于发送 WebSocket 帧的通道。帧由 Frame 类表示。
incoming
使用 incoming 属性访问用于接收 WebSocket 帧的通道。帧由 Frame 类表示。
close()
使用 close() 函数发送带有指定原因的关闭帧。

帧类型

您可以检查 WebSocket 帧的类型并进行相应处理。一些常见的帧类型包括:

  • Frame.Text 表示文本帧。使用 Frame.Text.readText() 读取其内容。
  • Frame.Binary 表示二进制帧。使用 Frame.Binary.readBytes() 读取其内容。
  • Frame.Close 表示关闭帧。使用 Frame.Close.readReason() 获取会话关闭的原因。

示例

以下示例创建了 echo WebSocket 端点,并展示了如何向服务器发送和接收消息。

kotlin
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。