【问题标题】:Sending message to Play Controller from Child Actors从子 Actor 向 Play Controller 发送消息
【发布时间】:2019-10-17 00:26:17
【问题描述】:

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

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

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

一旦子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) 
    }
}

【问题讨论】:

    标签: websocket playframework akka


    【解决方案1】:

    现在你正在用这条线创建一个新的演员

    val parentActor = actorSystem.actorOf(Props(new ParentActor(self)))
    

    如果您确定消息始终来自适当的 ParentActor,则无需创建新的 Actor,并且应该能够将消息发送给它

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

    【讨论】:

    • 谢谢。让我试试你的建议并回复
    猜你喜欢
    • 2021-09-11
    • 1970-01-01
    • 2017-06-29
    • 2013-04-30
    • 2015-05-29
    • 1970-01-01
    • 2021-11-22
    • 2015-12-09
    • 1970-01-01
    相关资源
    最近更新 更多