在Scala中播放2.2.2-WebSocket /等效的in.onClose()

时间:2014-04-25 13:42:03

标签: scala websocket akka playframework-2.2

我在Scala中使用Play 2.2.2。 我的控制器中有这个代码:

    def wsTest = WebSocket.using[JsValue] {
        implicit request =>
          val (out, channel) = Concurrent.broadcast[JsValue]
          val in = Iteratee.foreach[JsValue] {
            msg => println(msg)
          }
          userAuthenticatorRequest.tracked match { //detecting wheter the user is authenticated
            case Some(u) =>
              mySubscriber.start(u.id, channel)
            case _ =>
              channel push Json.toJson("{error: Sorry, you aren't authenticated yet}")
          }
          (in, out)
      }

调用此代码:

object MySubscriber {

  def start(userId: String, channel: Concurrent.Channel[JsValue]) {
    ctx.getBean(classOf[ActorSystem]).actorOf(Props(classOf[MySubscriber], Seq("comment"), channel), name = "mySubscriber") ! "start"
    //a simple refresh would involve a duplication of this actor!
  }

}

class MySubscriber(redisChannels: Seq[String], channel: Concurrent.Channel[JsValue]) extends RedisSubscriberActor(new InetSocketAddress("localhost", 6379), redisChannels, Nil) with ActorLogging {

  def onMessage(message: Message) {
    println(s"message received: $message")
    channel.push(Json.parse(message.data))
  }

  override def onPMessage(pmessage: PMessage) {
    //not used
    println(s"message received: $pmessage")
  }
}

问题是,当用户刷新页面时,新的websocket重新启动,涉及重复名为mySubscriber的Actors。

我注意到Play的Java版本有一种检测闭合连接的方法,以便关闭一个actor。 例如:

// When the socket is closed.
        in.onClose(new Callback0() {
           public void invoke() {
               // Shutdown the actor
               defaultRoom.shutdown();
           }
        });

如何使用Scala WebSocket API处理相同的事情?我想在每次关闭套接字时关闭actor。

1 个答案:

答案 0 :(得分:2)

正如@ Mik378所建议的那样,Iteratee.map扮演onClose的角色。

val in = Iteratee.foreach[JsValue] {
  msg => println(msg)
} map { _ =>
  println("Connection has closed")
}