1

playでactorから接続しているクライアントにbroadcastするにはどうしたらよいですか?

playでwebsocketを使うときの参考になるサイトがあったらぜひ教えて下さい。

//Global.scala
object Global extends GlobalSettings {

  override def onStart(app: Application) {
    val system = ActorSystem("system")
    val hello = system.actorOf(Props[HelloActor], "HelloActor")
    hello ! "world"
  }

}

//HelloActor.scala
class HelloActor extends Actor {
  def receive = {
    case "world" => helloWorld
  }

  def helloWorld = {
    val (out, channel) = Concurrent.broadcast[String]
    channel.push("HelloWorld!!")
  }
}

2 件の回答 2

1

https://www.playframework.com/documentation/2.3.x/ScalaWebSockets#Handling-WebSockets-with-iteratees

上のドキュメントにあるように下記のような方法でどうでしょうか?

import play.api.mvc._
import play.api.libs.iteratee._
import play.api.libs.concurrent.Execution.Implicits.defaultContext

def socket =  WebSocket.using[String] { request =>

  // Concurrent.broadcast returns (Enumerator, Concurrent.Channel)
  val (out, channel) = Concurrent.broadcast[String]

  // log the message to stdout and send response back to client
  val in = Iteratee.foreach[String] {
    msg => println(msg)
      // the Enumerator returned by Concurrent.broadcast subscribes to the channel and will
      // receive the pushed messages
      channel push("I received your message: " + msg)
  }
  (in,out)
}
6
  • 追記したように書いたのですが、actorとplayのcontextは別?なのかうまく行きません。実際の処理はActorをスケジュールで動かして、定期的に接続しているクライアントにデータを送信する、というものにしたいと思っております。 2015年5月13日 11:16
  • なるほど。そうすると、スケジューリングされて動いている Actor と WebSocket で接続されてる Actor は別のインスタンスになっているということですよね?
    – turutosiya
    2015年5月14日 0:02
  • はい。そういう解釈であってます。 2015年5月14日 1:09
  • コンテキストが同じであれば actorSelection でブロードキャストできますが、 「Actorをスケジュールで動かし」てる動かし方によっては、 WebSocket の Actor とスケジュールで動いている Actor が別コンテキストになっていると思うので、工夫しないといけないです。
    – turutosiya
    2015年5月14日 8:09
  • 解決しました。ありがとうございました! 2015年5月15日 12:06
1

ControllerにBroadcast用のデータのレシーバーを用意して、データを受信したらBroadcastするようにして解決しました。

//Application.scala
object Application extends Controller {

  var channel: MutableList[Concurrent.Channel[String]] = MutableList()

  def socket = WebSocket.using[String] { request =>
    val in = Iteratee.ignore[String]
    val out = Concurrent.unicast[String]{ c => channel += c }
    (in, out)
  }

  def reciever = Action { request =>
    channel.foreach(_.push(request.body.asJson.toString))
    Ok("success!")
  }
}


//HelloActor.scala
class HelloActor extends Actor {
    def receive = {
        case "Hello" => WS.url(url+"/product/info").withHeaders("Content-Type" -> "text/plain").post("Hello!")
        case _ =>
    }
}

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。