Play framework How to use akka streams output to a websocket

前提是你 提交于 2019-12-11 15:24:14

问题


Whats the easiest way to have the output of a flow be sent to a web socket in Playframework with Scala.

I want the WebSocket to act as the sink of the stream. For example the source generate a random number and then go to the sink (Websocket) so it is pushed to client.

Thanks


回答1:


If you are talking about the new Akka streams integration in Play 2.5.x (still M2), then I think this should do the job as a simple valid flow that represents an echo server (with a touch).

  def socket = WebSocket.accept[String, String] {
    request =>
      Flow[String]
        .map(_ + " Back")
  }



回答2:


"The easiest" is somewhat subjective, but you might consider Play's experimental reactive streams support as described here.

Include the Reactive Streams integration library into your project.

libraryDependencies += "com.typesafe.play" %% "play-streams-experimental" % "2.4.4"

All access to the module is through the Streams object.

Here is an example that adapts a Future into a single-element Publisher.

val fut: Future[Int] = Future { ... }
val pubr: Publisher[Int] = Streams.futureToPublisher(fut)

See the Streams object’s API documentation for more information.



来源:https://stackoverflow.com/questions/34341166/play-framework-how-to-use-akka-streams-output-to-a-websocket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!