WebSocket using Actors without Iteratees
The Play WebSocket API allows the use of Actors to define the behavior. Let's build the WebSocket application that replies with the reverse of a given String once it's connected. We can do this by slightly modifying our Reverser Actor to have an argument as the reference of the Actor to which it can/must send messages, as shown here:
class Reverser(outChannel: ActorRef) extends Actor {
def receive = {
case s: String => outChannel ! s.reverse
}
}
object Reverser {
def props(outChannel: ActorRef) = Props(classOf[Reverser], outChannel)
}The websocket can then be defined in a controller as follows:
def websocket = WebSocket.acceptWithActor[String, String] {
request => out =>
Reverser.props(out)
}Finally, we make an entry in the routes file:
GET /wsActor controllers.Application.websocket
We can now send messages through the WebSocket when the application is running using a browser plugin.
Now, lets...