Skip to content
Client Plugin

Ktor Client 中的 WebSockets

必要相依性:io.ktor:ktor-client-websockets

程式碼範例: client-websockets

WebSocket 是一種通訊協定,可透過單一 TCP 連線在使用者瀏覽器與伺服器之間提供全雙工通訊工作階段。它對於建立需要往返伺服器進行即時資料傳輸的應用程式特別有用。 Ktor 在伺服器端與用戶端均支援 WebSocket 協定。

用戶端的 Websockets 外掛程式可讓您處理與伺服器交換訊息的 WebSocket 工作階段。

並非所有引擎都支援 WebSockets。有關受支援引擎的概述,請參閱限制。

若要了解伺服器端的 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。