Comet是指基于 HTTP 长连接的“服务器推”技术,是一种不需要客户端主动请求,服务端可以主动给客户端推送消息的技术。
1.使用chunked response来实现Comet
chunked responses最主要的作用是创建Comet sockets。
一个Comet socket 只包含<script>
元素的是chunkedtest/html
响应。对于每一个chunk,我们写入一个包含JS的
2.导入comet
import akka.stream.Materializer import akka.stream.scaladsl.Source import play.api.http.ContentTypes import play.api.libs.Comet import play.api.libs.json._ import play.api.mvc._
除此之外也需要一个实例,最好是通过DI来注入一个akka.stream.Materializer
3.通过Flow推送字符串消息
def cometString = Action { implicit val m = materializer def stringSource: Source[String, _] = Source(List("kiki", "foo", "bar")) Ok.chunked(stringSource via Comet.string("parent.cometMessage")).as(ContentTypes.HTML) }
4.通过Flow推送JSON消息
def cometJson = Action { implicit val m = materializer def jsonSource: Source[JsValue, _] = Source(List(JsString("jsonString"))) Ok.chunked(jsonSource via Comet.json("parent.cometMessage")).as(ContentTypes.HTML) }
5.将Comet与iframe结合使用
Comet helper需要特别使用一种名为forever-iframe
的技术,如下html页面所示:
<script type="text/javascript"> var cometMessage = function(event) { console.log('Received event: ' + event) } </script> <iframe src="/comet"></iframe>
Note: 将如下配置添加到你的application.conf中,也要确保在routes中配置了正确的路由能够找到上面的action
play.filters.headers { frameOptions = "SAMEORIGIN" contentSecurityPolicy = "connect-src 'self'" }
有关Comet的示例,请参阅Play Streaming示例
6.Dubug Comet
最简单的方式是使用log()
操作来展示将数据映射到流中所出现的所有操作。