首页 > 解决方案 > Ktor websocket 客户端连接了多个服务器

问题描述

所以我正在创建一个分布式键值数据存储,并有一个代理来管理/查询。

这是我的客户:

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

     runBlocking {
         client.ws(
             method = HttpMethod.Get,
             host = ip,
             port = port,
             path = "/thepath"
         ) {
              ...
         }
     }
        
     client.close()

到目前为止,我只能将一台服务器连接到客户端(显然是上面的代码)。

我尝试的是创建所有可用服务器的数组并随机选择一个并与代理(客户端)一起工作。但这仅适用于连接的服务器,其他服务器应等到连接关闭。

        val clients: Array<HttpClient?> = arrayOfNulls(replicationFactor)
        for (i in 0 until replicationFactor) {
            clients[i] = HttpClient(CIO) {
                install(WebSockets)
            }
        }

        runBlocking {
            clients[0]?.ws(
                method = HttpMethod.Get,
                host = "some ip",
                port = the_port,
                path = "/thepath"
            ) {
               ....
            }

            ...
            ...
        }

关于如何解决这个问题的任何想法?也许我可以在单独的线程上保持与每个服务器的连接。

标签: kotlinwebsocketktor

解决方案


您可以创建任意数量的 HTTP 客户端并将它们同时连接到服务器。这是一个例子:

suspend fun main() {
    val clients = (0 until 3).map {
        HttpClient(CIO) {
            install(WebSockets)
        }
    }

    val connections = coroutineScope {
        clients.mapIndexed { index, client ->
            async {
                client.ws("wss://echo.websocket.org") {
                    outgoing.send(Frame.Text("Hello server"))

                    incoming.consumeEach { frame ->
                        if (frame is Frame.Text) {
                            println("[$index] Server replied ${frame.readText()}")
                        }
                    }
                }
            }
        }.toTypedArray()
    }

    awaitAll(*connections)
}

推荐阅读