Scala, Play, Akka, Websocket: how to pass actor messages through websocket

后端 未结 2 1940
臣服心动
臣服心动 2021-01-31 12:49

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

相关标签:
2条回答
  • 2021-01-31 13:12

    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)
    
        }   
    
    }
    
    0 讨论(0)
  • 2021-01-31 13:24

    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.

    0 讨论(0)
提交回复
热议问题