【问题标题】:how to get websocket working with play and Concurrent.broadcast如何让 websocket 与 play 和 Concurrent.broadcast 一起工作
【发布时间】: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


【解决方案1】:

您不会在客户端收到“hello world”,因为您在与客户端建立连接之前将其推送到频道。

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

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

【讨论】:

  • 我编辑了我的问题。所以通道会一直推送数据。为什么它仍然无法工作,因为在建立连接后它应该有可用的数据。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
  • 2012-12-09
  • 2014-06-06
  • 2017-01-20
  • 2017-05-08
  • 2014-12-25
  • 2010-09-14
相关资源
最近更新 更多