有没有办法使用 ktor WebSocket lib 检查 Android 设备上的连接状态?

Key*_*uzi 5 sockets android websocket kotlin ktor

有没有办法使用 ktor WebSocket lib 检查 Android 设备上的连接状态?我想在 WebSocet 连接或断开连接时发出通知。这有什么好玩的吗?

这是我的代码:

    try {

        client = HttpClient() {
            install(WebSockets) {
            }
        }
        client.ws(
            method = HttpMethod.Get,
            host = "hostName", path = "/ws"
        ) {

            send(Frame.Text("SampleText"))



                for (frame in incoming) {
                    when (frame) {
                       checkFrame()
                    }

                }
            }


    } catch (e: Exception) {
        Log.i(TAG, "${e.message} Exception")
Run Code Online (Sandbox Code Playgroud)

}

小智 0

您可以检查是否收到关闭帧:

 when (frame) {
   is Frame.Text ->  // Do text stuff here 
   is Frame.Close -> // Socket is closing/Closed
 }
Run Code Online (Sandbox Code Playgroud)

或者检查DefaultClientWebSocketSession是否有 closeReason:

if(webSocketSession?.closeReason != null) {
  // Socket closed
}
Run Code Online (Sandbox Code Playgroud)