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

Scala Concurrent类代码示例

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

本文整理汇总了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;未经允许,请勿转载。


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala Either类代码示例发布时间:2022-05-23
下一篇:
Scala Toolbar类代码示例发布时间: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