kyu999
kyu999

Reputation: 3

Cannot broadcast to all clients in play2

Now I'm working on WebSocket using Play2(Scala) and succeessfully communicate with client. However, the broadcast function that play offers seems not to send message to all clients. How can I fix it?

:Controller in server

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

  val (out, channel) = Concurrent.broadcast[String]

  val in = Iteratee.foreach[String] { msg => 

    println(msg)

    channel push(msg)  

    }.map{ _ => println("closed") } //when connection close

  (in, out)

  }

:Client Side

$ ->    


    ws = new WebSocket("ws://localhost:9000/ws")

    ws.onopen = (event) -> 

        console.log("connected!!")


    ws.onmessage = (event) ->

        data = event.data.split(",")

        infotype = data[0]

        if infotype is "noisy" 
            room = data[1]
            alert "noise happen at " + room

        else if infotype is "gotIt"
            console.log("someone gotIt")

        else 
            console.log(data)
            alert("oh arrive")


    ws.onerror = (event) -> 

        console.log("error happned")

    $(".rooms").on("click", (event) -> 
                    room = $(this).attr("id")
                    ws.send("noisy," + room) )

Ideally, when push the button(not button but just rooms class in this case), the client send message to the server(this works correctly) and server should broadcast that message to all clients(it did not work in my code). As a result, all clients should show the alert message. However, Only the client which sent message to the server can get the message from server and show the alert. What is the problem?

Upvotes: 0

Views: 127

Answers (1)

Nicolae Namolovan
Nicolae Namolovan

Reputation: 101

It's because you create a new Concurrent.broadcast for every client. Create it once outside your action, like this:

  val (out, channel) = Concurrent.broadcast[String]

  def ws = WebSocket.using[String] { request =>
    val in = Iteratee.foreach[String] { msg =>

      println(msg)

      channel push(msg)

      }.map{ _ => println("closed") } //when connection close

    (in, out)

  }

Upvotes: 1

Related Questions