Last active
March 12, 2016 10:26
-
-
Save yonex/5db290cc4853dfce9e8f to your computer and use it in GitHub Desktop.
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
| package controllers | |
| import javax.inject._ | |
| import akka.actor.{ActorSystem, Actor, ActorRef, Props} | |
| import akka.stream.Materializer | |
| import play.api.libs.json.Json | |
| import play.api.libs.streams.ActorFlow | |
| import play.api.mvc.WebSocket.MessageFlowTransformer | |
| import play.api.mvc._ | |
| @Singleton | |
| class WebSocketController @Inject() (implicit actorSystem: ActorSystem, materializer: Materializer) extends Controller { | |
| implicit val inEventFormat = Json.format[Ping] | |
| implicit val outEventFormat = Json.format[Pong] | |
| implicit val messageFlowTransformer = MessageFlowTransformer.jsonMessageFlowTransformer[Ping, Pong] | |
| def socket = WebSocket.accept[Ping, Pong] { request => | |
| ActorFlow.actorRef[Ping, Pong] { out => | |
| MyWebSocketActor.props(out) | |
| } | |
| } | |
| } | |
| case class Ping(ping: String = "ping") | |
| case class Pong(pong: String = "pong") | |
| object MyWebSocketActor { | |
| def props(out: ActorRef) = Props(new MyWebSocketActor(out)) | |
| } | |
| class MyWebSocketActor(out: ActorRef) extends Actor { | |
| def receive = { | |
| case ping: Ping => | |
| out ! Pong(ping.ping) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment