无法在Akka WebSocket中创建另一个actor

时间:2016-06-12 11:48:41

标签: scala playframework websocket akka

class HomeController  @Inject (implicit actorSystem:ActorSystem, materializer :Materializer) extends Controller 
{ 

    case class sendMsg(msg:JsValue)
    class MYWSACTOR(out:ActorRef,mainActor:ActorRef) extends Actor 
    {

        def receive = 
        {

            case msg : JsValue =>
            mainActor ! sendMsg(msg)

            case sendMsg(msg) => 
            {
                /* validation part */
                out ! msg
            }
        }

    }

}

val mainActor = actorSystem.actorOf(Props[MYWSACTOR],"mainActor")

def object MYWSACTOR 
{
    def props(out:ActorRef) = Props(new MYWSACTOR(out,mainActor))
}

def socket = WebSocket.accept[JsValue,JsValue] 
{ 
    request =>

    ActorFlow.actorRef(out => MYWSACTOR.props(out))

}

我是Akka和Scala的新手。我正在尝试使用Scala和Play框架2.5.3中的Akka进行聊天应用程序。我使用了官方文档中的上述代码。我只想创建另一个actor(上面代码中的mainActor),以便首先验证来自客户端的消息然后再发送回来。但问题是mainActor无法将msg发送到另一个类sendMsg。此外,如果我尝试在任何不同的点创建actor,它会给我编译错误意外异常:临时异常

1 个答案:

答案 0 :(得分:0)

希望你希望得到什么:

case class SendMsg(msg: JsValue)
case class ReceivedMessage(wsActor: ActorRef, msg: JsValue)

class MyWsActor(out: ActorRef, mainActor:ActorRef) extends Actor {

  def receive = {
    case msg : JsValue =>
      mainActor ! ReceivedMessage(self, msg)

    case SendMsg(msg) =>
      out ! msg
  }
}

object MyWsActor {
  def props(out: ActorRef, mainActor: ActorRef) = Props(new MyWsActor(out, mainActor))
  //or if you want to instantiate your Props with reflection
  def props2(out: ActorRef, mainActor: ActorRef) = Props(classOf[MyWsActor], out, mainActor)
}

class MainActor() extends Actor {
  def receive = {
    case ReceivedMessage(wsActor, msg) => {
      /*
      Do sth with msg
       */
      val result = msg
      wsActor ! SendMsg(result) //here sender is your MyWsActor
    }
  }
}

class HomeController  @Inject() (
    actorSystem: ActorSystem,
    materializer: Materializer
) extends Controller {

  val mainActor = actorSystem.actorOf(Props[MainActor], "mainActor")

  def socket = WebSocket.accept[JsValue,JsValue] {
      request =>
        ActorFlow.actorRef(out => MyWsActor.props(out, mainActor))
  }

}

关键是您可以使用实际消息发送ActorRef(或者默认情况下,您可以让发件人ActorRef调用sender()),然后您可以重播此ActorRef