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 try to implement dbWebSocket using this method:

 def dbCommunicator = WebSocket.acceptWithActor[JsValue, JsValue] {
    request => out =>
      WebSocketChannel.props(out)
  }

Here, WebSocketChannel is defined as follows:

class WebSocketChannel(out: ActorRef)
  extends Actor with ActorLogging {

  val backend = Akka.system.actorOf(DBActor.props)
  def receive: Actor.Receive = {
    case jsRequest: JsValue =>
      backend ! convertJsonToMsg(jsRequest)
    case x:DBResponse =>
      out ! x.toJson
  }
}

object WebSocketChannel {
  def props(out: ActorRef): Props =
    Props(classOf[WebSocketChannel], out)
}

The convertJsonToMsg method is responsible for translating JSON to a format that is accepted by the DBActor.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.76.138