Created
April 28, 2012 11:28
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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