Scala: Receiving Server-Sent-Events

时光总嘲笑我的痴心妄想 提交于 2019-12-03 12:42:46

You have several possibilities:

In Play 2.3, the WS library is now a separate library, so that should help. RC2 is already available

Alternatively, you could depend on Play 2.x and use a StaticApplication like so:

val application = new StaticApplication(new java.io.File("."))

This will essentially bootstrap a Play application, and from there on you can use the WS library as usual

I've accepted Manuel Bernhardt's answer because it led me in the right direction but I feel a full example is important for anyone else with this issue.

I updated my build.sbt file to include PlayWS 2.3 and the Iteratees library.

libraryDependencies ++= Seq(
  "com.typesafe.play" %% "play-ws" % "2.3.0",
  "com.typesafe.play" %% "play-iteratees" % "2.3.0"
)

The WS singleton requires an implicit Play Application to be used (something I don't have or want) so instead I will need to create my own client

val builder = new (com.ning.http.client.AsyncHttpClientConfig.Builder)()
val client = new play.api.libs.ws.ning.NingWSClient(builder.build())

I then create my Iteratee so that I can handle my server-sent-events.

def print = Iteratee.foreach { chunk: Array[Byte] => 
  println(new String(chunk))
}

and finally subscribe to the server

client.url("http://localhost:8080/topics/news").get(_ => print)

Now, when an event is sent

curl -X PUT server:port/topics/news -d "Politician Lies!"

My Scala application will print the received event

data: Politician Lies!

I'm not aware of other Scala libraries that implement a Server Sent Events client, but the Jersey project has a Java library for Server Sent Events clients (as well as servers). The API does not appear to be very verbose, and appears like it can be nicely wrapped in some code to fit in more idiomatically with Scala.

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