Broadcasting messages in Play Framework WebSockets

后端 未结 4 1396
闹比i
闹比i 2021-01-07 05:53

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

4条回答
  •  自闭症患者
    2021-01-07 06:25

    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)
        }
      }
    }
    

提交回复
热议问题