【发布时间】:2015-03-31 22:22:52
【问题描述】:
这是document 的建议,它确实有效。
import play.api.mvc._
import play.api.libs.iteratee._
import play.api.libs.concurrent.Execution.Implicits.defaultContext
def socket = WebSocket.using[String] { request =>
// Concurrent.broadcast returns (Enumerator, Concurrent.Channel)
val (out, channel) = Concurrent.broadcast[String]
// log the message to stdout and send response back to client
val in = Iteratee.foreach[String] {
msg => println(msg)
// the Enumerator returned by Concurrent.broadcast subscribes to the channel and will
// receive the pushed messages
channel push("I received your message: " + msg)
}
(in,out)
}
但是,如果我改为:
def socket = WebSocket.using[String] { request =>
val (out, channel) = Concurrent.broadcast[String]
val in=Iteratee.ignore[String]
channel push("Hello World")
(in,out)
}
如果您能帮助我理解为什么它不适用于新方法,我将不胜感激。
谢谢
詹姆斯
更新:
class ServiceHandler extends Actor {
import Tcp._
val (enumerator, channel) = Concurrent.broadcast[String]
val system=ActorDict.system
def receive = {
case subscribeData() =>{
sender ! enumerator
}
case Received(data) => {
val dst = data.decodeString("utf-8")
val va=dst.substring(dst.lastIndexOf(',') + 1).trim()
println(va)
channel.push(va)
}
case PeerClosed => context stop self
}
}
def ws = WebSocket.using[String] { request =>
val in=Iteratee.ignore[String]
val dataHandler = Akka.system.actorOf(Props[ServiceHandler])
val out= Await.result((dataHandler ? subscribeData()), 5 seconds).asInstanceOf[Enumerator[String]]
(in,out)
}
【问题讨论】:
-
我认为“不工作”是指没有任何东西被推回客户端。我只是猜测,但这可能是因为您在与客户端的连接完成之前推送到频道,所以他们没有收到该特定消息。
-
“不工作”是什么意思?
-
是的。这意味着客户端无法收到“hello world”消息。
-
我编辑了我的问题。所以通道会一直推送数据。为什么它仍然无法工作,因为在建立连接后它应该有可用的数据。谢谢!
标签: scala playframework websocket playframework-2.2 playframework-2.3