Skip to content

Instantly share code, notes, and snippets.

@fcroiseaux
Created April 28, 2012 11:28
Show Gist options
  • Save fcroiseaux/2518153 to your computer and use it in GitHub Desktop.
Save fcroiseaux/2518153 to your computer and use it in GitHub Desktop.
Comparison of Comet, SSE and WebSocket server to client communication with Playframework 2.0 in Scala
/**
* Handles the comet event stream.
*/
def cometStream = Action {
AsyncResult {
implicit val timeout = Timeout(5.seconds)
val actor=Akka.system.actorOf(Props[EventListener])
// Actor is listening for event on the eventStream
Akka.system.eventStream.subscribe(actor,classOf[ChangeEvent])
// For each event, stream the data to client
(actor ? "start").mapTo[Enumerator[JsValue]].asPromise.map { chunks =>
Ok.stream((chunks) &> Comet( callback = "parent.onEvent"))
}
}
}
/**
* Handles the SSE event stream.
*/
def eventSourceStream = Action {
AsyncResult
{
implicit val timeout = Timeout(5.seconds)
val actor=Akka.system.actorOf(Props[EventListener])
// Actor is listening for event on the eventStream
Akka.system.eventStream.subscribe(actor,classOf[ChangeEvent])
// For each event, stream the data to client
(actor ? "start").mapTo[Enumerator[JsValue]].asPromise.map { chunks =>
Ok.stream((chunks) &> EventSource()).as("text/event-stream")
}
}
}
/**
* Handles the websocket event stream.
*/
def listenEvents() = WebSocket.async[JsValue] { request =>
implicit val timeout = Timeout(5.seconds)
val actor=Akka.system.actorOf(Props[EventListener])
// Actor is listening for event on the eventStream
Akka.system.eventStream.subscribe(actor,classOf[ChangeEvent])
// For each event, stream the data to client
val iteratee = Iteratee.foreach[JsValue] {event => println(event)}
(actor ? "start").mapTo[Enumerator[JsValue]].asPromise.map {
chunks =>
(iteratee,chunks)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment