当前位置: 首页>>代码示例>>Scala>>正文


Scala Concurrent类代码示例

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


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

示例1: 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

示例2: 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

示例3: MyWebSocket

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

import de.htwg.se.setGame.controller.{NewGame, StartGame, UpdateGame}
import play.api.Logger
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.iteratee.{Concurrent, Iteratee}
import play.api.mvc.WebSocket
import scala.swing.Reactor


class MyWebSocket(private val manager: GameManager) extends Reactor {
  def get: WebSocket = WebSocket.using[String] { request =>
    val session = new SessionHandler(request.session)
    val controller = manager.get(session.getSessionId)
    val in = Iteratee.foreach[String](_ => {}).map { _ =>
      Logger.debug(MyWebSocket.Disconnect.format(session.getSessionId))
    }
    val (out, channel) = Concurrent.broadcast[String]
    Logger.debug(MyWebSocket.Connected.format(session.getSessionId))
    listenTo(controller.getController)

    reactions += {
      case e: NewGame =>
        Logger.debug(MyWebSocket.EventNewGame.format(session.getSessionId))
        channel.push(e.getClass.getName)
      case e: StartGame =>
        Logger.debug(MyWebSocket.EventStartGame.format(session.getSessionId))
        channel.push(e.getClass.getName)
      case e: UpdateGame =>
        Logger.debug(MyWebSocket.EventUpdateGame.format(session.getSessionId))
        channel.push(e.getClass.getName)
    }

    (in, out)
  }
}

object MyWebSocket {
  val Disconnect = "%s - disconnect from websocket"
  val Connected = "%s - connected to websocket"
  val EventNewGame = "%s - websocket received 'NewGame' event"
  val EventStartGame = "%s - websocket received 'StartGame' event"
  val EventUpdateGame = "%s - websocket received 'UpdateGame' event"
} 
开发者ID:phaldan,项目名称:htwg-set-game-scala-wui,代码行数:45,代码来源:MyWebSocket.scala

示例4: PublishableResult

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

import javax.inject.Inject

import akka.NotUsed
import akka.stream.scaladsl.Source
import com.google.inject.Singleton
import models.BusinessEvent
import play.api.libs.iteratee.Concurrent
import play.api.libs.streams.Streams

case class PublishableResult[RESULT, EVENT <: BusinessEvent](result: RESULT, events: Seq[EVENT])
case object PublishableResult {
  def apply[RESULT, EVENT <: BusinessEvent](res: RESULT, ev: EVENT): PublishableResult[RESULT, EVENT] = {
    PublishableResult(res, Seq(ev))
  }
}

trait EventPublisher {
  def publish[T <: BusinessEvent](event: T): T
  def subscribe: Source[BusinessEvent, NotUsed]

  def publishEventsAndReturnResult[RESULT, EVENT <: BusinessEvent](result: PublishableResult[RESULT, EVENT]): RESULT = {
    result.events.foreach(publish(_))
    result.result
  }
}


@Singleton
class ConcurrentBroadcastEventPublisher @Inject()() extends EventPublisher {

  val (eventsOut, eventsChannel) = Concurrent.broadcast[BusinessEvent]

  override def publish[T <: BusinessEvent](event: T): T = {
    eventsChannel.push(event)
    event
  }

  override def subscribe: Source[BusinessEvent, NotUsed] = Source
    .fromPublisher(Streams.enumeratorToPublisher(eventsOut))
} 
开发者ID:Antanukas,项目名称:play-reactive-workshop,代码行数:43,代码来源:EventPublisher.scala

示例5: 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

示例6: ScoreStreamer

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

import actors.TournamentEventActor.MatchCompleted
import akka.actor.Actor
import models.SeriesRound
import models.halls.{Hall, HallOverViewTournament}
import models.matches.{PingpongGame, PingpongMatch}
import models.player.{Player, Rank}
import play.api.libs.iteratee.Concurrent
import play.api.libs.json.{JsObject, Json}
import utils.{JsonUtils, StreamUtils}


object ScoreStreamer{
  case class Start(channel: Concurrent.Channel[JsObject])


  case class ShowCompletedMatch(pingpongMatch: PingpongMatch)
  case class ShowRound(name: String, color: String, seriesRound: SeriesRound)

}

class ScoreStreamer extends Actor{
  import ScoreStreamer._
  import models.SeriesRoundEvidence._
  implicit val rankFormat = Json.format[Rank]
  implicit val playerFormat = Json.format[Player]
  implicit val optionPlayerWrites = JsonUtils.optionWrites(playerFormat)
  implicit val gameWrites = Json.writes[PingpongGame]
  implicit val listGameWrites = JsonUtils.listWrites[PingpongGame]
  implicit val matchWrites = Json.writes[PingpongMatch]

  private var channel: Option[Concurrent.Channel[JsObject]] = None

  def receive: Receive = {
    case Start(outChannel: Concurrent.Channel[JsObject]) => this.channel = Some(outChannel)
    case ShowCompletedMatch(completedMatch: PingpongMatch) =>
      this.channel.foreach( realChannel => StreamUtils.pushJsonObjectToStream("completedMatch", completedMatch, realChannel))

    case ShowRound(name, color, roundToShow) =>
      val roundJson = Json.obj("round" -> Json.toJson(roundToShow), "name"-> name, "color" -> color)
      this.channel.foreach( realChannel => StreamUtils.pushJsonObjectToStream("roundToShow", roundJson, realChannel))
  }
} 
开发者ID:koenvanloock,项目名称:whifwhat,代码行数:45,代码来源:ScoreStreamer.scala

示例7: StreamActor

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

import akka.actor.Actor
import models.halls.{Hall, HallOverViewTournament}
import play.api.libs.json.{JsObject, Json}
import play.api.libs.iteratee.Concurrent


object StreamActor{

  case class Start(channel: Concurrent.Channel[JsObject])
  case class PublishActiveTournament(hallOverViewTournament: HallOverViewTournament)
  case class PublishActiveHall(hall: Hall)

}

class StreamActor extends Actor{
  import StreamActor._
  import models.halls.HallEvidence._
  import jsonconverters.HallTournamentOverviewWrites._
  private var channel: Option[Concurrent.Channel[JsObject]] = None

  def receive: Receive = {
    case Start(outChannel: Concurrent.Channel[JsObject]) => this.channel = Some(outChannel)
    case PublishActiveTournament(tournament: HallOverViewTournament) =>
      println("printing tournament to stream: " + tournament.tournamentName)
      this.channel.foreach(_.push(Json.obj("tournament" -> Json.toJson(tournament))))

    case PublishActiveHall(hall: Hall) =>
      println("printing hall to stream: " + hall.hallName)
      this.channel.foreach(_.push(Json.obj("hall" -> Json.toJson(hall))))
  }
} 
开发者ID:koenvanloock,项目名称:whifwhat,代码行数:34,代码来源:StreamActor.scala

示例8: 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

示例9: StreamUtils

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

import play.api.libs.iteratee.Concurrent
import play.api.libs.json.{JsObject, Json, Writes}

object StreamUtils {

  def pushJsonObjectToStream[A](objectDesc: String, objectToPush: A, channel: Concurrent.Channel[JsObject])(implicit aWrites: Writes[A]): Unit =
  {
    println(s"printing $objectDesc to scorestream: " + objectToPush)
    channel.push(Json.obj(objectDesc -> Json.toJson(objectToPush)(aWrites)))
  }


  def pushJsonObjectToStream(objectDesc: String, jsonObj: JsObject, channel: Concurrent.Channel[JsObject]): Unit =
  {
    println(s"printing $objectDesc to scorestream: " + jsonObj)
    channel.push(Json.obj(objectDesc -> jsonObj))
  }
} 
开发者ID:koenvanloock,项目名称:whifwhat,代码行数:21,代码来源:StreamUtils.scala


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