gpt4 book ai didi

scala - 如何使用akka客户端websocket向websocket服务器发出多个请求

转载 作者:行者123 更新时间:2023-12-05 07:02:47 24 4
gpt4 key购买 nike

我是 akka websockets 的新手,正在学习 akka 客户端 websockets https://doc.akka.io/docs/akka-http/current/client-side/websocket-support.html

我正在为我的 webrtc janus 服务器使用 websockets,因为我有 URL,我需要向它发送很多消息,每次都收到不同的响应,并根据该响应发送更多消息,我很困惑我们该怎么做通过查看示例代码,我认为每次需要向服务器发送消息时我都需要重复以下代码,但它似乎不正确,什么是正确的方法?

以我为例websocket 服务器正在运行ws://0.0.0.0:8188

首先我会向服务器发送消息以启动sessionID

request# 1

{
"janus" : "create",
"transaction" : "<random alphanumeric string>"
}

服务器将返回 session ID

response #1 
{
"janus": "success",
"session_id": 2630959283560140,
"transaction": "asqeasd4as3d4asdasddas",
"data": {
"id": 4574061985075210
}
}

然后根据 id 4574061985075210 我将发送另一条消息并接收更多信息

request # 02 {
}

response # 02 {
}
----

我如何使用 akka 客户端 websockets 实现这一点

这是我的代码

import akka.http.scaladsl.model.ws._

import scala.concurrent.Future

object WebSocketClientFlow {
def main(args: Array[String]) = {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
import system.dispatcher

val incoming: Sink[Message, Future[Done]] =
Sink.foreach[Message] {
case message: TextMessage.Strict =>
println(message.text)
//suppose here based on the server response i need to send another message to the server and so on do i need to repeat this same code here again ?????

}

val outgoing = Source.single(TextMessage("hello world!"))

val webSocketFlow = Http().webSocketClientFlow(WebSocketRequest("ws://echo.websocket.org"))

val (upgradeResponse, closed) =
outgoing
.viaMat(webSocketFlow)(Keep.right) // keep the materialized Future[WebSocketUpgradeResponse]
.toMat(incoming)(Keep.both) // also keep the Future[Done]
.run()

val connected = upgradeResponse.flatMap { upgrade =>
if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
Future.successful(Done)
} else {
throw new RuntimeException(s"Connection failed: ${upgrade.response.status}")
}
}

connected.onComplete(println)
closed.foreach(_ => println("closed"))
}
}

最佳答案

我建议您访问此网站并查看文档。 IT 拥有您需要的所有信息。

https://doc.akka.io/docs/akka/current/typed/actors.html

关于scala - 如何使用akka客户端websocket向websocket服务器发出多个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63426143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com