I have an actor which is launched with application, running in the background watching for certain changes and if there are any reporting them. At the moment it just a pri
I have found the solution.
Case class that has to be imported from a separate file:
case class Start(out: Concurrent.Channel[String])
Global object:
object Global extends GlobalSettings {
override def onStart(app: Application) {
class Listener extends Actor {
var out = {
val (enum, chan) = Concurrent.broadcast[String]
chan
}
def receive = {
//Websocket channel out is set here
case Start(out) => this.out = out
//Pushing messages to Websocket
case Create(path) => this.out.push(path.toString)
case Delete(path) => this.out.push(path.toString)
case Modify(path) => this.out.push(path.toString)
}
}
val listener = Akka.system.actorOf(Props[Listener], "listener")
val swatch = Akka.system.actorOf(Props[SwatchActor], "swatch")
swatch ! Watch("/folder/path", Seq(Create, Modify, Delete), true, Option(listener))
}
}
Play controller:
object Application extends Controller {
def test = WebSocket.using[String] { request =>
val (out, channel) = Concurrent.broadcast[String]
val listener = Akka.system.actorSelection("akka://application/user/listener")
//This is where the websocket out channel is being passed to the listener actor
listener ! Start(channel)
val in = Iteratee.foreach[String] { msg =>
channel push("RESPONSE: " + msg)
}
(in, out)
}
}
Just the other day I wrote this, which will be included in Play 2.3. You can copy it to your own application for now:
https://github.com/jroper/ReactiveMaps/blob/websocket-actor/app/actors/WebSocketActor.scala
You pass it a Props object, and it will create the actor for you. You send to the WebSocket by sending to context.parent.