无法播放play2中的所有客户端

时间:2014-05-31 05:50:56

标签: scala playframework websocket playframework-2.0 broadcast

现在我正在使用Play2(Scala)开发WebSocket,并成功地与客户端进行通信。但是,播放提供的广播功能似乎不向所有客户端发送消息。我该如何解决?

:服务器中的控制器

  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)

  }

:客户端

$ ->    


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

理想情况下,按下按钮(不是按钮,但在这种情况下只是房间类),客户端向服务器发送消息(这可以正常工作),服务器应该将消息广播给所有客户端(它在我的代码中不起作用) )。 因此,所有客户端都应显示警报消息。 但是,只有向服务器发送消息的客户端才能从服务器获取消息并显示警报。 有什么问题?

1 个答案:

答案 0 :(得分:1)

这是因为您为每个客户端创建了一个新的Concurrent.broadcast。 在行动之外创建一次,如下所示:

  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)

  }