从儿童演员向播放控制器发送消息

Sending message to Play Controller from Child Actors

我不清楚如何将消息传递给具有将 actorRef 作为参数的构造函数的 actor。

我正在尝试使用 Play Framework 实现一个简单的 websocket 服务器。

我在 Controller 中接收客户端请求,我可以将请求传递给父 Actor(将 actorRef 作为构造函数参数),后者又将请求传递给子 actor。

一旦子演员处理了请求,我就无法将响应发送回控制器。

@Singleton
class RequestController @Inject()(cc: ControllerComponents)(implicit system: ActorSystem, mat: Materializer) extends AbstractController(cc) {
    def ws = WebSocket.accept[String, String] {req =>
    ActorFlow.actorRef { out =>
      ParentActor.props(out)
    }
  }
}
=======
object ParentActor {
  def props(out: ActorRef) = Props(new ParentActor(out))
}

class ParentActor(out : ActorRef) extends Actor {
implicit val actorSystem = ActorSystem("ab")
    override def receive: Receive = {
         case msg: String => 
            val childActor: ActorRef = actorSystem.actorOf(Props[ChildActor])
            childActor ! msg
         case msg: Response => out ! msg
    }
}
==================
case class Response(name:String, msg:String)
class ChildActor extends Actor{
implicit val actorSystem = ActorSystem("cd")
    override def receive: Receive = {
        case msg : String => 
        // Below statement is not working. I tried with sender() instead of self
        // which is also not working
        val parentActor = actorSystem.actorOf(Props(new ParentActor(self))) 
        parentActor ! Response("ABC",msg) 
    }
}

现在您正在使用

行创建一个新演员
val parentActor = actorSystem.actorOf(Props(new ParentActor(self)))

如果您确定消息始终来自相应的 ParentActor,则无需创建新的 actor,并且应该能够使用

向其发送消息
sender() ! Response("ABC", message)