简体   繁体   中英

Play framework How to use akka streams output to a websocket

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

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")
  }

"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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM