• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala EventSource类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中play.api.libs.EventSource的典型用法代码示例。如果您正苦于以下问题:Scala EventSource类的具体用法?Scala EventSource怎么用?Scala EventSource使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了EventSource类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: ScalaEventSourceController

//设置package包名称以及导入依赖的类
package controllers

import java.io.File

import play.Play
import java.nio.file.Paths
import javax.inject.{Inject, Singleton}

import play.api.http.ContentTypes
import play.api.libs.EventSource
import play.api.mvc._

@Singleton
class ScalaEventSourceController @Inject()(cc: ControllerComponents) extends AbstractController(cc) with ScalaTicker {

  def index() = Action {
    Ok(views.html.scalaeventsource())
  }

  def streamClock() = Action {
    Ok.chunked(stringSource via EventSource.flow).as(ContentTypes.EVENT_STREAM)
  }

  def upload = Action(parse.multipartFormData) { request =>
    request.body.file("picture").map { picture =>
      var basePath = "/app/public/upload/"

      var archivoTmp = new File(basePath)
      if(!archivoTmp.exists()) {
        basePath = Play.application().getFile("/public/upload/").getAbsolutePath() + File.separator;
      }

      val filename = picture.filename
      val contentType = picture.contentType
      picture.ref.moveTo(Paths.get(basePath + filename), replace = true)
      reiniciarSimulacion();
      Ok(views.html.scalaeventsource())
    }.getOrElse {
      Redirect(routes.ScalaEventSourceController.index).flashing(
        "error" -> "Missing file")
    }
  }

} 
开发者ID:juancamilogaviriaacosta,项目名称:proyecto-transmimetro-JuanGaviria-MauricioMontano,代码行数:45,代码来源:ScalaEventSourceController.scala


示例2: Application

//设置package包名称以及导入依赖的类
package controllers

import play.api._
import play.api.mvc._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import play.api.libs.concurrent.Akka
import play.api.Play.current
import models._

import play.api.libs.EventSource
import play.api.libs.iteratee._

class Application extends Controller {

  val (out, channel) = Concurrent.broadcast[String]
  val listener = Akka.system.actorSelection("akka://application/user/listener")
  listener ! Start(channel)

  def dashboard = Action {
    Ok(views.html.dashboard())
  }

  def index = Action {
    Ok(views.html.index("Your new application is ready."))
  }
  def createNewUser = Action.async {
    listener ! UserRegistration
    Future.successful(Ok(""))
  }

  def sendMessage = Action.async {
    listener ! NewMessage
    Future.successful(Ok(""))
  }
  def stream = Action { implicit req =>
        Ok.feed(out &> EventSource()).as("text/event-stream")
  }
}

object Application extends Application 
开发者ID:clrvynt,项目名称:sse,代码行数:42,代码来源:Application.scala


示例3: index

//设置package包名称以及导入依赖的类
package controllers

import javax.inject._

import play.api._
import play.api.libs.EventSource
import play.api.libs.iteratee.Concurrent
import play.api.libs.json.JsValue
import play.api.mvc._



  val (chatOut, chatChannel) = Concurrent.broadcast[JsValue]

  def index = Action { implicit request =>
    Ok(views.html.index(routes.HomeController.chatFeed(), routes.HomeController.postMessage()))
  }

  def chatFeed = Action { request =>
    println("Someone has connected" + request.remoteAddress)
    Ok.chunked(chatOut
      &> EventSource()
    ).as("text/event-stream")
  }

  def postMessage = Action(parse.json) { request =>
    chatChannel.push(request.body)
    Ok
  }

} 
开发者ID:RyanOM,项目名称:playChat,代码行数:32,代码来源:HomeController.scala


示例4: MainController

//设置package包名称以及导入依赖的类
package controllers

import java.util.UUID

import actors.EventStreamActor
import akka.actor.ActorSystem
import akka.stream.Materializer
import akka.stream.actor.ActorPublisher
import akka.stream.scaladsl.{Sink, Source}
import model._
import play.api.libs.EventSource
import play.api.libs.json.JsValue
import play.api.mvc._
import security.{UserAuthAction, UserAwareAction, UserAwareRequest}
import services.{ConsumerAggregator, RewindService}


class MainController(userAuthAction: UserAuthAction,
                     userAwareAction: UserAwareAction,
                     actorSystem: ActorSystem,
                     consumerAggregator: ConsumerAggregator,
                     rewindService: RewindService,
                     mat: Materializer) extends Controller {

  def serverEventStream = userAwareAction { request =>
    implicit val materializer = mat
    implicit val actorFactory = actorSystem

    val maybeUser = request.user
    val maybeUserId = maybeUser.map(_.userId)
    val actorRef = actorFactory.actorOf(EventStreamActor.props,
      EventStreamActor.name(maybeUserId))
    val eventStorePublisher = Source.fromPublisher(ActorPublisher[JsValue](actorRef))
      .runWith(Sink.asPublisher(fanout = true))
    val source = Source.fromPublisher(eventStorePublisher)
    Ok.chunked(source.via(EventSource.flow)).as("text/event-stream")
  }
  
  def rewind = Action {
    request =>
      rewindService.refreshState(); Ok
  }

  def index = userAwareAction { request =>
    Ok(views.html.pages.react(buildNavData(request),
      WebPageData("Home")))
  }

  def error500 = Action {
    InternalServerError(views.html.errorPage())
  }

  private def buildNavData(request: UserAwareRequest[_]): NavigationData = {
    NavigationData(request.user, isLoggedIn = request.user.isDefined)
  }
} 
开发者ID:getArtemUsername,项目名称:play-and-events,代码行数:57,代码来源:MainController.scala


示例5: hashtagLoad

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.Inject

import akka.actor.ActorSystem
import akka.stream.Materializer
import akka.stream.scaladsl.Flow
import com.datastax.driver.core.Session
import controllers.stages.LoadStage
import play.api.libs.EventSource
import play.api.mvc.{Action, Controller}
import services.utils.CassandraHelper._
import services.utils.{CassandraHelper, CassandraUri}
import services.{Hashtag, MyTwitterListener, Tweet}

import scala.concurrent.ExecutionContext


  def hashtagLoad = Action {
    val source = twitterListener.hashtagSource

    val loadFlow = LoadStage.getFlow(loadHashtags)
    //Flow stage using take, as the limit function throws an exception when threshold is exceeded
    val filter = Flow[Set[Hashtag]].take(MAX_TWEETS)

    val hashtagSource = source.via(filter).via(loadFlow)

    Ok.chunked(hashtagSource.map(set ? set.mkString) via EventSource.flow)

  }


  private def loadHashtags(s: Session, hashtags: Set[Hashtag]) = {
    for (hashTag ? hashtags) {
      s.execute(s"UPDATE $HASHTAG_TABLE SET hashtag_count = hashtag_count + 1 WHERE hashtag='" + hashTag.name.replace("'", "") + "';")
    }
  }
} 
开发者ID:pmarteen,项目名称:twitterstream,代码行数:39,代码来源:CassandraController.scala


示例6: ChatController

//设置package包名称以及导入依赖的类
package controllers

import models.{User, ChatRoom}
import play.api.data._
import play.api.data.Forms._
import play.api.libs.EventSource
import play.api.libs.iteratee.{Enumeratee, Concurrent}
import play.api.libs.json.JsValue
import play.api.mvc.{WebSocket, Action, Controller}
import play.api.libs.concurrent.Execution.Implicits._

object ChatController extends Controller {

  def index = Action { implicit request =>
    Ok(views.html.chat())
  }

  
  def chatWS(username: String) = WebSocket.tryAccept[JsValue] { request  =>

    ChatRoom.join(username).map{ io =>
      Right(io)
    }.recover{ case e => Left(Ok(e))}
  }

  def chatSSE(username: String) = Action.async { request =>
    ChatRoom.join(username).map{ io =>
      Ok.feed(io._2
        &> Concurrent.buffer(50)
        &> Enumeratee.onIterateeDone{ () =>
          play.Logger.info(request.remoteAddress + " - SSE disconnected")
        }
        &> EventSource()).as("text/event-stream")
    }.recover{ case e => BadRequest(e)}
  }

  val talkForm = Form(
    tuple(
      "username" -> nonEmptyText,
      "msg" -> text
    )
  )

  def talk = Action{ implicit request =>
    talkForm.bindFromRequest.fold(
      error => BadRequest,
      value => {
        ChatRoom.talk(value._1, value._2)
        Ok
      }
    )
  }

} 
开发者ID:gurghet,项目名称:rota-scalajs2,代码行数:55,代码来源:ChatController.scala


示例7: HubController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.{Inject, Singleton}

import akka.stream.Materializer
import akka.stream.scaladsl.{BroadcastHub, Keep, MergeHub, Source}
import models.Message
import play.api.http.ContentTypes
import play.api.libs.EventSource
import play.api.mvc._

@Singleton
class HubController @Inject() (implicit val mat: Materializer) extends Controller {

  private[this] val (sink, source) =
    MergeHub.source[String](perProducerBufferSize = 16)
      .toMat(BroadcastHub.sink(bufferSize = 256))(Keep.both)
      .run()

  def index = Action {
    Ok(views.html.hub())
  }

  def receiveMessage = Action(BodyParsers.parse.json[Message]) { request =>
    Source.single(request.body.toString).runWith(sink)
    Ok
  }

  def sse = Action {
    Ok.chunked(source via EventSource.flow).as(ContentTypes.EVENT_STREAM)
  }

} 
开发者ID:septeni-original,项目名称:play-scala-sse-example,代码行数:34,代码来源:HubController.scala


示例8: MainController

//设置package包名称以及导入依赖的类
package controllers

import play.api.mvc.{Action, Controller}
import process._

import play.api.libs.EventSource
import play.api.libs.iteratee._

class MainController extends Controller {

  val (out, channel) = Concurrent.broadcast[String]
  val dataReader = DataReader(channel)
  dataReader.start()

  def index() = Action {
    Ok(views.html.index())
  }

  def classifiedTweets() = Action { implicit req =>
    Ok.feed(out &> EventSource()).as("text/event-stream")
  }
} 
开发者ID:GRpro,项目名称:TwitterAnalytics,代码行数:23,代码来源:MainController.scala


示例9: index

//设置package包名称以及导入依赖的类
package controllers

import javax.inject._
import play.api._
import play.api.mvc._
import twitter4j.conf.ConfigurationBuilder
import play.api.libs.iteratee.Enumeratee
import twitter4j._
import twitter4j.{Status => TwitterStatus}
import twitter4j.auth._
import twitter4j.conf._
import play.api.libs.json._
import scala.concurrent.ExecutionContext.Implicits.global
import services._
import play.api.libs.EventSource


  def index = Action {
    Ok(views.html.index("Your new application is ready."))
  }
  
  
  
  def stream(query: String) = Action {
    val queries = query.split(",")
    val streams = queries.map { query =>  
      val twitterListener = new TwitterStreamListener(query, config)  
      twitterListener.listenAndStream
    }
    
    val mixStreams = streams.reduce((s1, s2) => s1 interleave s2)
    val jsonMixStreams = mixStreams through toJson
    
    Ok.chunked(jsonMixStreams through EventSource()).as("text/event-stream")
  }
  

} 
开发者ID:getmetorajesh,项目名称:rj_play_twitterstream_sse,代码行数:39,代码来源:HomeController.scala


示例10: ChatApplication

//设置package包名称以及导入依赖的类
package controllers

import play.api.mvc._
import play.api.libs.json.JsValue
import play.api.libs.iteratee.{Concurrent, Enumeratee}
import play.api.libs.EventSource
import play.api.libs.concurrent.Execution.Implicits._

object ChatApplication extends Controller {

  
  def chatFeed(room: String) = Action { req =>
    println(req.remoteAddress + " - SSE connected")
    Ok.feed(chatOut
      &> filter(room) 
      &> Concurrent.buffer(50) 
      &> connDeathWatch(req.remoteAddress)
      &> EventSource()
    ).as("text/event-stream") 
  }

} 
开发者ID:oceanpad,项目名称:sse-chat,代码行数:23,代码来源:ChatApplication.scala


示例11: StreamController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.{Inject, Named}

import actors.ScoreStreamer
import actors.StreamActor.Start
import actors.TournamentEventActor.SetChannel
import akka.actor.ActorRef
import akka.util.Timeout
import play.api.libs.json.JsObject
import play.api.mvc.{Action, Controller}

import scala.concurrent.duration._
import akka.stream.scaladsl.Source
import play.api.libs.EventSource
import play.api.libs.iteratee.{Concurrent, Enumerator}
import play.api.libs.streams.Streams

import scala.concurrent.ExecutionContext.Implicits.global

class StreamController @Inject()(@Named("score-streamer") scoreStreamer: ActorRef, @Named("stream-actor") streamActor: ActorRef, @Named("tournament-event-actor") tournamentEventActor: ActorRef) extends Controller {
  implicit val timeout = Timeout(5 seconds)

  val (out, channel) = Concurrent.broadcast[JsObject]
  streamActor ! Start(channel)

  val (scoreOut, scoreChanel) = Concurrent.broadcast[JsObject]
  scoreStreamer ! ScoreStreamer.Start(scoreChanel)

  tournamentEventActor ! SetChannel(streamActor)

  def tournamentEventStream = Action { implicit req => enumeratorToStream(out)}

  def scoreEventStream = Action { implicit req => enumeratorToStream(scoreOut)}

  private def enumeratorToStream(enumerator: Enumerator[JsObject]) = {
    val source: Source[String, Any] = Source.fromPublisher(Streams.enumeratorToPublisher(enumerator.map(x => x.toString())))
    Ok.chunked(source via EventSource.flow).as("text/event-stream")
  }
} 
开发者ID:koenvanloock,项目名称:whifwhat,代码行数:41,代码来源:StreamController.scala



注:本文中的play.api.libs.EventSource类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Resources类代码示例发布时间:2022-05-23
下一篇:
Scala OAuth2Info类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap