如何在 Ktor websockets 上发送 ping

How to send pings on Ktor websockets

我尝试在 api 文档和示例中进行搜索,但没有任何示例演示如何发送 ping 和接收 ping。唯一的例子是如何连接到 websocket 和发送文本 here。 我还看到了服务器端的聊天示例 here,我也仔细地遵循了它(即在 WebSocket 安装的服务器端配置中设置 ping 间隔)。

我开始监听双方的 pong 声,但 none 方正在接收任何 ping 消息。

并且没有为 ping 配置客户端的选项,如您所见here

我对如何发送 ping 感到非常困惑。

这是我的服务器端:

embeddedServer(
    CIO,
    80
) {
    install(io.ktor.websocket.WebSockets) {
        pingPeriod = Duration.ofSeconds(20)
    }

    routing {
        webSocket("/ws") {
            for (frame in incoming) {
                when (frame) {
                    is Frame.Pong -> {
                        println("ping's response recieved")
                    }

                    is Frame.Ping -> {
                        // just temporary block
                        println("ping recieved")
                    }

                    is Frame.Text -> {
                        println(frame.readText())
                    }
                }
            }
        }
    }
}.apply { start() }

这是我的客户端:

val client = HttpClient(CIO) {
    install(WebSockets)
}

client.ws(
    method = HttpMethod.Get,
    host = "127.0.0.1",
    port = 80,
    path = "/ws"
) {

    send(Frame.Text("Hello World!"))

    for (frame in incoming) {
        when (frame) {
            is Frame.Pong -> {
                println("ping's response received")
            }

            is Frame.Ping -> {
                // just temporary block
                println("ping recieved from server")
            }

            is Frame.Text -> {
                println(frame.readText())
            }
        }
    }
}

结果:

Hello World!

即 websocket 已连接,可以传输文本,但不幸的是不能使用 ping/pong 功能。

我还找到了这个 here pingerponger 的一些函数,但现在它说它是 api 的一部分,并自动启动 WebsocketSession 和我还尝试将 pinger 放在客户端,但无论如何都不会向服务器发送 ping。

以上代码的结果只是 Hello world 从客户端发送到服务器控制台,但没有收到任何 ping 消息。

我在使用 OkHttp 时遇到了问题 ping/pong 所以我提交了这个问题 https://github.com/ktorio/ktor/issues/1803 并且其中一位开发人员回复了 "well the only thing I can recommend you is to try CIO out. Is does support manual Ping/Pong processing using RawWebSockets."

我自己还没有尝试过,但你应该看看 https://github.com/ktorio/ktor/blob/master/ktor-features/ktor-websockets/jvm/test/io/ktor/tests/websocket/RawWebSocketTest.kt