Last active
January 23, 2017 21:53
-
-
Save irumiha/4954330 to your computer and use it in GitHub Desktop.
play-2.1.0-chat
This file contains 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
// This is the part in the Controller that creates the EventSource connection | |
def liveListen(event: String) = Action { request => | |
AsyncResult { | |
implicit val timeout: Timeout = 5.seconds | |
(MegaRoomActor.ref ? (MegaRoomActor.Join(event)) ). | |
mapTo[Enumerator[JsValue]].map(startEventStream) | |
} | |
} | |
def startEventStream(e: Enumerator[JsValue]) = | |
Ok.stream(e &> EventSource()).withHeaders( | |
"Content-Type" -> "text/event-stream", | |
"Cache-Control" -> "no-cache", | |
"Connection" -> "keep-alive", | |
"Access-Control-Allow-Origin" -> "*" | |
) | |
This file contains 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
// This is the part of the actor that handles the chat rooms and pushes messages to clients | |
case Join(roomname) => { | |
if (rooms.contains(roomname)) { | |
val newuuid = UUID.randomUUID() | |
val ch: Enumerator[JsValue] = Concurrent.unicast[JsValue]( | |
onStart = (c) => { | |
Logger.info("Client add to room %s".format(roomname)) | |
rooms(roomname) += (newuuid -> c) | |
}, | |
onComplete ={ () => | |
self ! Quit(roomname, newuuid) | |
}, | |
onError = (str, in) => { | |
Logger.info(str) | |
self ! Quit(roomname,newuuid) | |
} | |
).onDoneEnumerating(() => | |
self ! Quit(roomname, newuuid) | |
) | |
sender ! ch | |
} | |
else { | |
sender ! Enumerator.eof[String] | |
} | |
} | |
case Quit(roomname,ch) => { | |
Logger.info("Chat client disconnect requested") | |
if (rooms.contains(roomname)){ | |
Logger.info("Chat client disconnect") | |
rooms(roomname) -= ch | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment