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 ...

Get Mastering Play Framework for Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.