问题描述
我是akka websocket的新手,正在学习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
首先,我将向服务器发送一条消息以启动会话ID
@H_404_9@request# 1 { "janus" : "create","transaction" : "<random alphanumeric string>" }
服务器将使用会话ID进行响应
@H_404_9@response #1 { "janus": "success","session_id": 2630959283560140,"transaction": "asqeasd4as3d4asdasddas","data": { "id": 4574061985075210 } }
然后基于ID 4574061985075210,我将发送另一条消息并接收更多信息
@H_404_9@request # 02 { } response # 02 { } ----
我如何使用Akka客户端Websocket实现这一目标
这是我的代码
@H_404_9@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拥有您所需的所有信息。