I\'m pushing messages in Play Framework WebSockets using Concurrent.unicast[JsValue]
, and I want to optimize sending the same message to multiple users. Is it p
From my experiments, Concurrent.broadcast
does not send to everyone (some unfortunate naming perhaps?)
Here is what I used that works as expected.
package controllers
import play.api._
import play.api.mvc._
import play.api.libs.iteratee.Concurrent
import play.api.libs.iteratee.Iteratee
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import scala.collection.mutable.{Set => MS}
import scala.concurrent._
object Application extends Controller {
val c:MS[(Int, Concurrent.Channel[String])] = MS() // (channelID, Channel))
def pushHello = c.foreach(_._2.push("hello")) // push to ALL channels
def index = WebSocket.async[String] { _ => future{
val (out,channel) = Concurrent.broadcast[String]
val channelID = scala.util.Random.nextInt
c.add((channelID, channel))
val in = Iteratee.foreach[String] {
_ match {
case any => channel.push("received:"+any) // push to current channel
}
}.map { _ => c.retain(x => x._1 != channelID) }
(in, out)
}
}
}