如何让websocket与play和Concurrent.broadcast一起工作

时间:2015-03-31 22:22:53

标签: scala playframework websocket playframework-2.2 playframework-2.3

以下是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)
  }

1 个答案:

答案 0 :(得分:0)

你不会收到"你好世界"在客户端,因为您在与客户建立连接之前将其推送到频道。

如果您不需要从客户端接收任何内容(这就是您执行val in=Iteratee.ignore[String]的原因)您最好使用服务器发送的事件:

Ok.chunked(out &> EventSource()).as("text/event-stream")