从子演员向游戏控制器发送消息



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

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

我在控制器中收到客户端请求,我可以将请求传递给父参与者(它将 actorRef 作为构造函数参数(,而父参与者又将请求传递给子参与者。

子参与者处理了请求后,我无法将响应发回控制器。

@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,则无需创建新的参与者,并且应该能够通过以下方式向其发送消息

sender() ! Response("ABC", message)

最新更新