现在我正在使用Play2(Scala)进行WebSocket工作,并成功与客户端进行通信。然而,play提供的广播功能似乎并没有向所有客户端发送消息。我该怎么修理它?
: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)
}
:客户端
$ ->
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) )
理想情况下,当按下按钮(不是按钮,而只是房间类在这种情况下),客户端发送消息到服务器(这工作正确)和服务器应该广播该消息到所有的客户端(它没有在我的代码工作)。因此,所有客户端都应该显示警报消息。但是,只有向服务器发送消息的客户端才能从服务器获取消息并显示警报。有什么问题吗?
这是因为你创建了一个新的Concurrent。广播每个客户端。在操作之外创建它,像这样:
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)
}