kotlin - 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"
) {
....
}
...
...
}
关于如何解决这个问题的任何想法?也许我可以在单独的线程上保持与每个服务器的连接。
解决方案
您可以创建任意数量的 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)
}
推荐阅读
- r - 如何将一个非常大的 .dat 文件拆分为 XML 文件?
- html - 我如何给一个html div位置动态高度
- oracle - 是否有任何存储 Oracle APEX 使用日志的表
- java - 如何将所选电影的数据获取到detailActivity,然后获取到详细活动中的片段?
- python - 从jpg文件恢复灰度图像
- python - 在python中,如果抛出错误,我如何重新运行函数
- python-3.x - Python Random 没有函数不运行就刷新
- python - 获取分离子进程的返回码?
- python - 比较单词列表中的用户输入
- sql - 从数据表中提取数据到 JPA 中的文本文件