【发布时间】:2020-08-15 12:39:20
【问题描述】:
我是 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>"
}
服务器将使用会话 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"))
}
}
【问题讨论】:
-
我个人更喜欢直接使用与 akka-streams 不同的方法,即创建一个表示与您的服务器的 websocket 连接的参与者,您应该有一个表示实际的参与者的引用ws 连接到服务器,我还没有为客户端做这个,但是如果这个评论还不够,我可以尝试一下。演员表现得更好,因为大多数时候你在与 websocket 服务器的连接之间有一个可变状态。
-
很久没接触akka-streams了,另一种方法是在
incomingsink之前定义outgoing源,这样源在处理传入的函数上可见消息,然后,希望将另一个项目提供给此类源流(将自动发送到您的 websocket 服务器)很简单。 -
显然,这就是我在第一条评论中所指的:doc.akka.io/docs/akka/current/stream/operators/ActorSource/…
-
你能用一个例子解释你的第一条评论吗,这对我来说可能更清楚,很有帮助
-
@AlexITC 你能看看吗stackoverflow.com/questions/63505847/…
标签: scala websocket akka akka-http