Book Image

Mastering Play Framework for Scala

By : Shiti Saxena
Book Image

Mastering Play Framework for Scala

By: Shiti Saxena

Overview of this book

Table of Contents (21 chapters)
Mastering Play Framework for Scala
About the Author
About the Reviewers
Free Chapter
Getting Started with Play

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

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