我刚接触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上。
首先,我将向服务器发送一条消息以启动会话ID。
request# 1
{
"janus" : "create",
"transaction" : "<random alphanumeric string>"
}
服务器将会返回会话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"))
}
}