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

Scala ActorSelection类代码示例

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

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



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

示例1: PipeableFuture

//设置package包名称以及导入依赖的类
package akka.pattern

import language.implicitConversions
import scala.concurrent.{ Future, ExecutionContext }
import scala.util.{ Failure, Success }
import akka.actor.{ Status, ActorRef, Actor }
import akka.actor.ActorSelection

trait PipeToSupport {

  final class PipeableFuture[T](val future: Future[T])(implicit executionContext: ExecutionContext) {
    def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): Future[T] = {
      future onComplete {
        case Success(r) ? recipient ! r
        case Failure(f) ? recipient ! Status.Failure(f)
      }
      future
    }
    def pipeToSelection(recipient: ActorSelection)(implicit sender: ActorRef = Actor.noSender): Future[T] = {
      future onComplete {
        case Success(r) ? recipient ! r
        case Failure(f) ? recipient ! Status.Failure(f)
      }
      future
    }
    def to(recipient: ActorRef): PipeableFuture[T] = to(recipient, Actor.noSender)
    def to(recipient: ActorRef, sender: ActorRef): PipeableFuture[T] = {
      pipeTo(recipient)(sender)
      this
    }
    def to(recipient: ActorSelection): PipeableFuture[T] = to(recipient, Actor.noSender)
    def to(recipient: ActorSelection, sender: ActorRef): PipeableFuture[T] = {
      pipeToSelection(recipient)(sender)
      this
    }
  }

  
  implicit def pipe[T](future: Future[T])(implicit executionContext: ExecutionContext): PipeableFuture[T] = new PipeableFuture(future)
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:41,代码来源:PipeToSupport.scala


示例2: ActorRefEx

//设置package包名称以及导入依赖的类
package com.udemy.akka.actorpath

import akka.actor.{ActorRef, ActorSelection, ActorSystem, PoisonPill, Props}


object ActorRefEx extends App{
  val system=ActorSystem("PathSystem")
  private val counter1: ActorRef = system.actorOf(Props[Counter],"counter")
  println(s"Actor reference for counter $counter1")
  private val counterSelection: ActorSelection = system.actorSelection("counter")
  println(s"Actor selection  for counter $counterSelection")
  counter1 ! PoisonPill
  Thread.sleep(100)
  private val counter2: ActorRef = system.actorOf(Props[Counter],"counter")
  println(s"Actor reference for counter $counter2")
  private val counterSelection2: ActorSelection = system.actorSelection("counter")
  println(s"Actor selection  for counter $counterSelection2")
  system.terminate()
} 
开发者ID:akshay-harale,项目名称:udemy-akka,代码行数:20,代码来源:ActorRefEx.scala


示例3: Endpoint

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

import akka.actor.{ Actor, ActorSelection }
import akka.pattern.{ ask }
import akka.util.{ Timeout }

import types.Messages._

object Endpoint {
}

class Endpoint extends Actor {
  import Endpoint._

  val requests = collection.mutable.Map[ Integer, List[ActorSelection] ]()

  def receive = {
    case AskFor(number) =>
      val askerPath = sender().path.parent.parent./("user")./("Computer")
      val askerSel = context.actorSelection(askerPath)
      requests get number match {
        case Some(list) =>
          if(!list.contains(askerSel))
            requests put (number, askerSel :: list)
        case None =>
          requests put (number, List(askerSel))
      }
      sender ! Registered
    case AnswerFor(number, isPrime) =>
      if(requests isDefinedAt number){
        val askers = requests(number)
        askers.map (ref => ref ! AnswerFor(number,isPrime))
      }
      requests remove number
  }

} 
开发者ID:snate,项目名称:sieves_of_Eratosthenes,代码行数:38,代码来源:Endpoint.scala


示例4: RaftClient

//设置package包名称以及导入依赖的类
package ru.ifmo.ctddev.semenov.dkvs.client

import akka.actor.{Actor, ActorLogging, ActorSelection, ActorSystem, PoisonPill, Props}
import ru.ifmo.ctddev.semenov.dkvs.protocol.Command

import scala.util.{Failure, Success, Try}


class RaftClient(node: ActorSelection) extends Actor with ActorLogging {
  import RaftClient._

  override def receive: Receive = {
    case ConsoleMessage(msg) => Try(Command(msg)) match {
      case Success(command)   => node ! command
      case Failure(exception) => log.error(exception, "illegal command?..")
    }
    case RaftResponse(msg)   =>
      println(msg)
    case Exit                =>
      self ! PoisonPill // graceful stop after processing remaining events
  }
}

object RaftClient {
  sealed trait Message
  case class ConsoleMessage(msg: String) extends Message
  case class RaftResponse(msg: String) extends Message
  case object Exit extends Message

  def props(node: ActorSelection) = Props(classOf[RaftClient], node)

  def main(args: Array[String]) {
    if (args.length != 3) {
      println("Usage: RaftClient <host> <port> <id>")
    } else {
      val (host, port, id) = (args(0), args(1), args(2))
      // TODO: check config
      val system = ActorSystem("raft-client")
      // it's irrational, that user should know (host,port,id) of node,
      // it should connect to cluster, not to specific node. isn't it?
      // TODO: add address to config or constant
      // TODO: add option to connect to cluster
      val clusterNode = system.actorSelection(s"akka.tcp://[email protected]$host:$port/user/dkvs-$id")
      val client = system.actorOf(props(clusterNode), "raftClient")
      for (line <- scala.io.Source.stdin.getLines()) {
        client ! ConsoleMessage(line.trim)
      }
      client ! Exit
    }
  }
} 
开发者ID:vadimsemenov,项目名称:distributed-key-value-storage,代码行数:52,代码来源:RaftClient.scala


示例5: UserActor

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

import akka.actor.{Actor, ActorRef, ActorSelection, Props}
import akka.cluster.pubsub.DistributedPubSub
import akka.cluster.pubsub.DistributedPubSubMediator.{Subscribe, SubscribeAck}
import models.{ToPublish, _}
import play.api.libs.json.Json
import models.Formats._
import models.MsgTypes._

class UserActor(out: ActorRef) extends Actor {

  val mediator: ActorRef = DistributedPubSub(context.system).mediator
  mediator ! Subscribe("content", self)

  val publisher: ActorSelection = context.system.actorSelection("/user/publisher")
  val playlist: ActorSelection = context.system.actorSelection("/user/playlist")

  playlist ! GetPlaylist

  def receive = {
    case SubscribeAck(Subscribe("content", None, `self`)) ? println("subscribing")

    case msg: Payload if msg.event == PUBLISH =>
      publisher ! ToPublish(msg)
    case ToPublish(payload) =>
      out ! payload

    case msg: Payload if msg.event == PLAY || msg.event == STOP =>
      playlist ! msg
    case msg: Payload if msg.event == NEXT =>
      playlist ! PlayNext
    case msg: Payload if msg.event == ADD =>
      playlist ! AddToPlaylist(msg.content.get)
    case msg: Payload if msg.event == CLEAR =>
      playlist ! ClearPlaylist
      publisher ! ToPublish(msg)
    case msg: Playlist =>
      out ! Payload(PLAYLIST, Some(Json.toJson(msg).toString()))

    case Payload(event, content) =>
      out ! Payload("response", content)
  }
}

object UserActor {
  def props(out: ActorRef) = Props(new UserActor(out))
} 
开发者ID:oen9,项目名称:bard-api,代码行数:49,代码来源:UserActor.scala


示例6: PlanNotifier

//设置package包名称以及导入依赖的类
package lila.plan

import akka.actor.ActorSelection
import scala.concurrent.duration._

import lila.hub.actorApi.timeline.{ Propagate }
import lila.notify.Notification.Notifies
import lila.notify.{ Notification, NotifyApi }
import lila.user.User

private[plan] final class PlanNotifier(
    notifyApi: NotifyApi,
    scheduler: lila.common.Scheduler,
    timeline: ActorSelection
) {

  def onStart(user: User) = fuccess {
    scheduler.once(5 seconds) {
      notifyApi.addNotification(Notification.make(
        Notifies(user.id),
        lila.notify.PlanStart(user.id)
      ))
    }
    val msg = Propagate(lila.hub.actorApi.timeline.PlanStart(user.id))
    timeline ! (msg toFollowersOf user.id)
  }

  def onExpire(user: User) =
    notifyApi.addNotification(Notification.make(
      Notifies(user.id),
      lila.notify.PlanExpire(user.id)
    ))
} 
开发者ID:DrNixx,项目名称:line,代码行数:34,代码来源:PlanNotifier.scala


示例7: Messenger

//设置package包名称以及导入依赖的类
package lila.round

import akka.actor.ActorSelection

import actorApi._
import lila.chat.actorApi._
import lila.game.Game
import lila.i18n.I18nKey.{ Select => SelectI18nKey }
import lila.i18n.I18nKeys

final class Messenger(
    val chat: ActorSelection,
    i18nKeys: I18nKeys
) {

  def system(game: Game, message: SelectI18nKey, args: Any*) {
    val translated = message(i18nKeys).en(args: _*)
    chat ! SystemTalk(watcherId(game.id), translated)
    if (game.nonAi) chat ! SystemTalk(game.id, translated)
  }

  def systemForOwners(gameId: String, message: SelectI18nKey, args: Any*) {
    val translated = message(i18nKeys).en(args: _*)
    chat ! SystemTalk(gameId, translated)
  }

  def watcher(gameId: String, member: Member, text: String) =
    member.userId foreach { userId =>
      chat ! UserTalk(watcherId(gameId), userId, text)
    }

  private val whisperCommands = List("/whisper ", "/w ")

  def owner(gameId: String, member: Member, text: String) = (member.userId match {
    case Some(userId) =>
      whisperCommands.collectFirst {
        case command if text startsWith command =>
          UserTalk(watcherId(gameId), userId, text drop command.size)
      } orElse {
        if (text startsWith "/") none // mistyped command?
        else UserTalk(gameId, userId, text, public = false).some
      }
    case None =>
      PlayerTalk(gameId, member.color.white, text).some
  }) foreach chat.!

  private def watcherId(gameId: String) = s"$gameId/w"
} 
开发者ID:DrNixx,项目名称:line,代码行数:49,代码来源:Messenger.scala


示例8: Notifier

//设置package包名称以及导入依赖的类
package lila.qa

import lila.hub.actorApi.timeline.{ Propagate, QaQuestion, QaAnswer, QaComment }
import lila.notify.Notification.Notifies
import lila.notify.{ Notification, NotifyApi }
import lila.user.User

import akka.actor.ActorSelection

private[qa] final class Notifier(
    notifyApi: NotifyApi,
    timeline: ActorSelection
) {

  private[qa] def createQuestion(q: Question, u: User) {
    val msg = Propagate(QaQuestion(u.id, q.id, q.title))
    timeline ! (msg toFollowersOf u.id)
  }

  private[qa] def createAnswer(q: Question, a: Answer, u: User) {
    val msg = Propagate(QaAnswer(u.id, q.id, q.title, a.id))
    timeline ! (msg toFollowersOf u.id toUser q.userId exceptUser u.id)
    if (u.id != q.userId) notifyAsker(q, a)
  }

  private[qa] def notifyAsker(q: Question, a: Answer) = {
    import lila.notify.QaAnswer
    import lila.common.String.shorten

    val answererId = QaAnswer.AnswererId(a.userId)
    val question = QaAnswer.Question(id = q.id, slug = q.slug, title = shorten(q.title, 80))
    val answerId = QaAnswer.AnswerId(a.id)

    val notificationContent = QaAnswer(answererId, question, answerId)
    val notification = Notification.make(Notifies(q.userId), notificationContent)

    notifyApi.addNotification(notification)
  }

  private[qa] def createQuestionComment(q: Question, c: Comment, u: User) {
    val msg = Propagate(QaComment(u.id, q.id, q.title, c.id))
    timeline ! (msg toFollowersOf u.id toUser q.userId exceptUser u.id)
  }

  private[qa] def createAnswerComment(q: Question, a: Answer, c: Comment, u: User) {
    val msg = Propagate(QaComment(u.id, q.id, q.title, c.id))
    timeline ! (msg toFollowersOf u.id toUser a.userId exceptUser u.id)
  }
} 
开发者ID:DrNixx,项目名称:line,代码行数:50,代码来源:Notifier.scala


示例9: Analyser

//设置package包名称以及导入依赖的类
package lila.analyse

import akka.actor.ActorSelection

import chess.format.FEN
import lila.game.actorApi.InsertGame
import lila.game.GameRepo
import lila.hub.actorApi.map.Tell

final class Analyser(
    indexer: ActorSelection,
    requesterApi: RequesterApi,
    roundSocket: ActorSelection,
    bus: lila.common.Bus
) {

  def get(id: String): Fu[Option[Analysis]] = AnalysisRepo byId id

  def save(analysis: Analysis): Funit = GameRepo game analysis.id flatMap {
    _ ?? { game =>
      GameRepo.setAnalysed(game.id)
      AnalysisRepo.save(analysis) >>
        sendAnalysisProgress(analysis) >>- {
          bus.publish(actorApi.AnalysisReady(game, analysis), 'analysisReady)
          indexer ! InsertGame(game)
          requesterApi save analysis
        }
    }
  }

  def progress(analysis: Analysis): Funit = sendAnalysisProgress(analysis)

  private def sendAnalysisProgress(analysis: Analysis): Funit =
    GameRepo gameWithInitialFen analysis.id map {
      _ ?? {
        case (game, initialFen) =>
          roundSocket ! Tell(analysis.id, actorApi.AnalysisProgress(
            analysis = analysis,
            game = game,
            variant = game.variant,
            initialFen = initialFen | FEN(game.variant.initialFen)
          ))
      }
    }
} 
开发者ID:DrNixx,项目名称:line,代码行数:46,代码来源:Analyser.scala


示例10: Cli

//设置package包名称以及导入依赖的类
package lila.api

import akka.actor.ActorSelection

import lila.hub.actorApi.Deploy

private[api] final class Cli(bus: lila.common.Bus, renderer: ActorSelection) extends lila.common.Cli {

  private val logger = lila.log("cli")

  def apply(args: List[String]): Fu[String] = run(args).map(_ + "\n") ~ {
    _.logFailure(logger, _ => args mkString " ") foreach { output =>
      logger.info("%s\n%s".format(args mkString " ", output))
    }
  }

  def process = {
    case "deploy" :: "pre" :: Nil => remindDeploy(lila.hub.actorApi.DeployPre)
    case "deploy" :: "post" :: Nil => remindDeploy(lila.hub.actorApi.DeployPost)
  }

  private def remindDeploy(event: Deploy): Fu[String] = {
    bus.publish(event, 'deploy)
    fuccess("Deploy in progress")
  }

  private def run(args: List[String]): Fu[String] = {
    (processors lift args) | fufail("Unknown command: " + args.mkString(" "))
  } recover {
    case e: Exception => "ERROR " + e
  }

  private def processors =
    lila.user.Env.current.cli.process orElse
      lila.security.Env.current.cli.process orElse
      lila.i18n.Env.current.cli.process orElse
      lila.gameSearch.Env.current.cli.process orElse
      lila.teamSearch.Env.current.cli.process orElse
      lila.forumSearch.Env.current.cli.process orElse
      lila.team.Env.current.cli.process orElse
      lila.puzzle.Env.current.cli.process orElse
      lila.tournament.Env.current.cli.process orElse
      lila.explorer.Env.current.cli.process orElse
      lila.fishnet.Env.current.cli.process orElse
      lila.blog.Env.current.cli.process orElse
      lila.study.Env.current.cli.process orElse
      lila.studySearch.Env.current.cli.process orElse
      lila.coach.Env.current.cli.process orElse
      lila.evalCache.Env.current.cli.process orElse
      process
} 
开发者ID:DrNixx,项目名称:line,代码行数:52,代码来源:Cli.scala


示例11: PizzaClient

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

import akka.actor.{Actor, ActorRef, ActorSelection, Address, Props, RelativeActorPath, RootActorPath}
import akka.actor.Actor.Receive
import akka.cluster.Cluster
import akka.cluster.ClusterEvent._
import messages._

import scala.concurrent.forkjoin.ThreadLocalRandom


object PizzaClient {
  def props(servicePath: String)(user: ActorRef) = Props(classOf[PizzaClient], servicePath, user)
}

class PizzaClient(servicePath: String, user: ActorRef) extends Actor {
  val cluster = Cluster(context.system)
  var nodes = Set.empty[Address]
  val servicePathElements = servicePath match {
    case RelativeActorPath(elements) => elements
    case _ => throw new IllegalArgumentException("servicePath [%s] is not a valid relative actor path" format servicePath)
  }

  override def preStart(): Unit = {
    cluster.subscribe(self, initialStateMode = InitialStateAsEvents, classOf[MemberEvent], classOf[ReachabilityEvent])
  }

  override def postStop(): Unit = {
    cluster.unsubscribe(self)
  }

  override def receive: Receive = {
    case order: PizzaCustomerOrder => {
      // find service actor
      val service = findServiceActor()
      service ! order
    }
    case stop: PizzaCustomerStop => {
      // find service actor
      val service = findServiceActor()
      service ! stop
    }
    case result: PizzaCustomerBaked => {
      user ! result
    }
    case PizzaCustomerPing => sender() ! PizzaCustomerPong
    case MemberUp(m) if m.hasRole("chef") => nodes += m.address
    case ReachableMember(m) if m.hasRole("chef") => nodes += m.address
    case otherMemberEvent: MemberEvent => nodes -= otherMemberEvent.member.address
    case UnreachableMember(m) => nodes -= m.address
  }

  private def findServiceActor(): ActorSelection = {
    // for load balance, select random master proxy
    val address = nodes.toIndexedSeq(ThreadLocalRandom.current.nextInt(nodes.size))
    context.actorSelection(RootActorPath(address) / servicePathElements)
  }
} 
开发者ID:prokosna,项目名称:pizza-baker,代码行数:59,代码来源:PizzaClient.scala


示例12: RoomClientActor

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

import java.util.UUID

import akka.actor.{Actor, ActorLogging, ActorRef, ActorSelection, Props}
import commands.{ListPublicRoomsCommand, NewMessageCommand, UserJoinRoomCommand, UserLeftRoomCommand}
import events.{JoinedChannelEvent, NewMessageEvent, RoomEventType}
import json.{IncomingRoomMessage, OutgoingRoomMessage}
import org.joda.time.DateTime


class RoomClientActor(actorRef: ActorRef, userId: String) extends Actor with ActorLogging {
  
  var roomMasterActor: ActorSelection = _
  
  @scala.throws[Exception](classOf[Exception])
  override def preStart(): Unit = {
    super.preStart()
    roomMasterActor = context.actorSelection("/user/" + RoomMasterActor.getClass.getSimpleName)
  }
  
  override def receive: Receive = {
    case msg: IncomingRoomMessage => processIncomingRoomMessage(msg)
    case msg: JoinedChannelEvent => actorRef ! new OutgoingRoomMessage(msg.channelId, msg.userId, RoomEventType.JOIN.toString, None, DateTime.now().getMillis)
    case msg: NewMessageEvent => actorRef ! new OutgoingRoomMessage(msg.from, msg.from, RoomEventType.MESSAGE.toString, Option(msg.text), msg.timestamp)
    case msg: Any => unhandled(msg)
  }
  
  def processIncomingRoomMessage(msg: IncomingRoomMessage): Unit = {
    val eventType = RoomEventType.withName(msg.eventType)
    
    eventType match {
      case RoomEventType.JOIN => {
        roomMasterActor ! new UserJoinRoomCommand(msg.roomId, userId)
      }
      case RoomEventType.MESSAGE => {
        msg.text match {
          case text: Some[String] => roomMasterActor ! new NewMessageCommand(userId, msg.roomId, msg.text.get, UUID.randomUUID().toString, DateTime.now.getMillis)
          case None => sender() ! "Invalid message"
        }
      }
      case RoomEventType.LEAVE => roomMasterActor ! new UserLeftRoomCommand(msg.roomId, userId)
      case RoomEventType.LIST => roomMasterActor ! new ListPublicRoomsCommand
    }
  }
  
}

object RoomClientActor {
  def props(actorRef: ActorRef, userId: String) = Props(new RoomClientActor(actorRef, userId))
} 
开发者ID:dazito,项目名称:messengr,代码行数:52,代码来源:RoomClientActor.scala


示例13: DestinationsFeedWSConnection

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

import akka.actor.{Actor, ActorRef, ActorSelection, Props}
import play.api.Logger
import play.api.libs.json.JsValue

class DestinationsFeedWSConnection(destinationFeedManager: ActorSelection, out: ActorRef)
  extends Actor with DestinationFeedProtocolParser with FeedResponseGenerator {

  def receive = {
    case jsonRequest: JsValue =>
      parseAndHandle(jsonRequest)
    case SubscriptionFeed(json) =>
      out ! constructJsonResponse(LiveFeed(json))
    case other =>
      println("UNHANDLED MESSAGE")
      println(other)
  }

  override def postStop() {
    Logger.info("Client unsubscribing from stream")
    destinationFeedManager ! UnSubscribeToFeed
  }

  private def parseAndHandle(jsonRequest: JsValue) = {
    handleRequest(parseRequest(jsonRequest))
  }

  private def handleRequest(request: DestinationFeedProtocol) = request match {
    case DestinationFeedSubscriptionRequest =>
      out ! constructJsonResponse(Subscribing)
      destinationFeedManager ! SubscribeToFeed

    case DestinationFeedUnSubscriptionRequest =>
      destinationFeedManager ! UnSubscribeToFeed

    case DestinationFeedUnknownRequest =>
      out ! constructJsonResponse(UnknownRequest)
  }
}

object DestinationsFeedWSConnection {
  def props(destinationFeedManager: ActorSelection, out: ActorRef) =
    Props(new DestinationsFeedWSConnection(destinationFeedManager, out))
} 
开发者ID:aerohit,项目名称:TravellingWhere,代码行数:46,代码来源:DestinationsFeedWSConnection.scala


示例14: TaxRateProducer

//设置package包名称以及导入依赖的类
package scb.tpcdi

import akka.actor.{Actor, ActorLogging, ActorSelection}
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration._


class TaxRateProducer extends Actor with ActorLogging {
  import context.dispatcher

  implicit val timeout = Timeout(2 seconds)

  var da = None : Option[ActorSelection] // DataAccess actor with circuit breaker
  val rnd = new java.util.Random()

  case class Tick()
  val ticker =
    context.system.scheduler.schedule(5 seconds, 500 millis, self, Tick())

  override def postStop() = ticker.cancel()

  def receive = {
    case Tick() => 
      da match {
        case None => 
          da = Some(context.actorSelection("/user/dataaccess/singleton")) 
        case Some(da) => 
          ask(da, nextTaxRate()) onFailure {
            case e => log.error("Error: {}", e)
          } 
      }
  }

  def nextTaxRate(): TaxRate = {
    TaxRate("US1", 
      "U.S. Income Tax Bracket for the poor", 
      rnd.nextDouble())
      //(math floor rnd.nextDouble() * 1E5) / 1E2)
  } 
} 
开发者ID:bahadley,项目名称:adaptive-circuit-breaker,代码行数:42,代码来源:TaxRateProducer.scala


示例15: SignonActor

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

import akka.actor.{Actor, ActorSelection}
import akka.event.Logging
import operation.trivia.entities._

import scala.collection.mutable.ArrayBuffer


class SignonActor extends Actor {

  private[SignonActor] val players: ArrayBuffer[Player] = ArrayBuffer[Player]()
  private[SignonActor] val log = Logging(context.system, this)
  private[SignonActor] val hostActorSelection =
    context.system.actorSelection("akka.tcp://[email protected]:2553/user/hostActor")

  override def receive: Receive = {
    case SignOn(p:Player) =>
      log.debug("Signing on player: {}", p)
      players += p
      if (players.nonEmpty) {
        log.debug("Single player signed on, starting game")
        hostActorSelection ! GameStart
      }
    case SignOff(p:Player) =>
      //No more players, stop the game
      log.debug("Signing off player: {}", p)
      players -= p
      if (players.isEmpty) {
        log.debug("No players signed on, stopping game")
        hostActorSelection ! GameStop
      }
  }
} 
开发者ID:dhinojosa,项目名称:operation-trivia,代码行数:35,代码来源:SignonActor.scala


示例16: ScorekeeperWebSocketActor

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

import akka.actor.{Actor, ActorRef, ActorSelection, Props}
import akka.event.Logging
import operation.trivia.entities._
import play.api.Logger
import play.api.libs.json._

object ScorekeeperWebSocketActor {
  def props(out: ActorRef) = Props(new ScorekeeperWebSocketActor(out))
}

class ScorekeeperWebSocketActor(out: ActorRef) extends Actor {

  val actorSelection: ActorSelection =
    context.actorSelection("akka.tcp://[email protected]:2555/user/scoreKeeperActor")

  def receive: PartialFunction[Any, Unit] = {
    case "init" =>
      Logger.info("ScoreKeeperWebSocketActor Received: init")
      actorSelection ! Register(self)
    case s: String =>
      //Answer arrived from the web
      Logger.info(s"ScoreKeeperWebSocketActor Received String: $s")
      val json: JsValue = Json.parse(s)
      actorSelection ! Answer(Player((json \ "name").as[String]), (json \ "answer").as[Int])
    case RoundResults(persons) =>
      Logger.info(s"Round Results: $persons")
      out ! Json.stringify(Json.obj("round-results" -> Json.toJson(persons.map(p => p.name))))
    case QuestionResults(persons) =>
      Logger.info(s"Question Results: $persons")
      out ! Json.stringify(Json.obj("question-results" -> Json.toJson(persons.map(p => p.name))))
    case o =>
      Logger.info(s"ScoreKeeperWebSocketActor Received Unknown: $o")
      unhandled(o)
  }

  override def postStop(): Unit = {
    Logger.info("Actor stopping")
    actorSelection ! Unregister(self)
  }
} 
开发者ID:dhinojosa,项目名称:operation-trivia,代码行数:43,代码来源:ScorekeeperWebSocketActor.scala


示例17: HostWebSocketActor

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

import akka.actor.{Actor, ActorRef, ActorSelection, Props}
import operation.trivia.entities._
import play.api.Logger
import play.api.libs.json._

object HostWebSocketActor {
  def props(out: ActorRef) = Props(new HostWebSocketActor(out))
}

class HostWebSocketActor(out: ActorRef) extends Actor {
  val actorSelection: ActorSelection =
    context.actorSelection("akka.tcp://[email protected]:2553/user/hostActor")

  def receive: PartialFunction[Any, Unit] = {
    case "init" =>
      Logger.debug("Init connection Host")
      actorSelection ! Register(self)
    case q: Question =>
      Logger.debug("Question Delivered to Web!")
      val json: JsValue = Json.toJson(
        Json.obj("question" -> Json.obj("item" -> q.item, "possibleAnswers" ->
          q.possibleAnswers, "actualAnswer" -> q.actualAnswer))
      )
      out ! Json.stringify(json)
    case y: Int =>
      Logger.debug("Got an int message:" + y)
      out ! Json.stringify(Json.obj("secondsLeft" -> y))
    case None =>
      Logger.debug("There are no questions")
      out ! Json.stringify(Json.obj("error" -> "no questions"))
    case RoundNext(n) =>
      Logger.debug("Next Round:" + n)
      out ! Json.stringify(Json.obj("round" -> Json.obj("status" -> "next", "number" -> n)))
    case RoundStop =>
      Logger.debug("Round Stop:")
      out ! Json.stringify(Json.obj("round" -> Json.obj("status" -> "stop")))
    case RoundStart =>
      Logger.debug("Round Start:")
      out ! Json.stringify(Json.obj("round" -> Json.obj("status" -> "start")))
    case m =>
      Logger.debug("Didn't find anything for" + m)
  }

  override def postStop(): Unit = {
    actorSelection ! Unregister(self)
  }
} 
开发者ID:dhinojosa,项目名称:operation-trivia,代码行数:50,代码来源:HostWebSocketActor.scala


示例18: SignonWebSocketActor

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

import akka.actor.{Actor, ActorRef, ActorSelection, Props}
import akka.event.Logging

object SignonWebSocketActor {
  def props(out: ActorRef) = Props(new ScorekeeperWebSocketActor(out))
}

class SignonWebSocketActor(out: ActorRef) extends Actor {
  val log = Logging(context.system, this)
  val actorSelection: ActorSelection =
    context.actorSelection("akka.tcp://[email protected]:2556/user/signonActor")

  def receive: PartialFunction[Any, Unit] = {
    case content: String => println("Got content" + content)
  }
} 
开发者ID:dhinojosa,项目名称:operation-trivia,代码行数:19,代码来源:SignonWebSocketActor.scala


示例19: QuestionController

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

import javax.inject._

import akka.actor.{ActorSelection, ActorSystem}
import operation.trivia.entities.Question
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc._
import play.api.Logger

class QuestionController @Inject()(val webJarAssets: WebJarAssets,
                                   val actorSystem: ActorSystem,
                                   val messagesApi: MessagesApi)
  extends Controller with I18nSupport {

  val questionForm = Form(
    mapping(
      "item" -> nonEmptyText,
      "possibleAnswers" -> list(text),
      "actualAnswer" -> number
    )(Question.apply)(Question.unapply)
  )

  val questionActor: ActorSelection = actorSystem.actorSelection(
    "akka.tcp://[email protected]:2554/user/questionActor")

  def getQuestionForm = Action {implicit request =>
    Ok(views.html.question.question("Create Question", questionForm, webJarAssets))
  }

  def index = Action {implicit request =>
    Ok(views.html.question.index("Create Question", webJarAssets))
  }

  def processQuestion = Action {implicit request =>
    questionForm.bindFromRequest.fold(
      formWithErrors => {
        BadRequest(views.html.question.question("Create Question", formWithErrors, webJarAssets))
      },
      question => {
        Logger.debug(s"Sending Question: ${question.toString}")
        questionActor ! question
        Logger.debug(s"Question Sent: ${question.toString}")
        Redirect(routes.QuestionController.index())
      }
    )
  }
} 
开发者ID:dhinojosa,项目名称:operation-trivia,代码行数:51,代码来源:QuestionController.scala


示例20: Messenger

//设置package包名称以及导入依赖的类
package lila.round

import akka.actor.ActorSelection

import actorApi._
import lila.chat.actorApi._
import lila.game.Game
import lila.i18n.I18nKey.{ Select => SelectI18nKey }
import lila.i18n.{ I18nKeys, enLang }

final class Messenger(val chat: ActorSelection) {

  def system(game: Game, message: SelectI18nKey, args: Any*) {
    val translated = message(I18nKeys).literalTxtTo(enLang, args)
    chat ! SystemTalk(watcherId(game.id), translated)
    if (game.nonAi) chat ! SystemTalk(game.id, translated)
  }

  def systemForOwners(gameId: String, message: SelectI18nKey, args: Any*) {
    val translated = message(I18nKeys).literalTxtTo(enLang, args)
    chat ! SystemTalk(gameId, translated)
  }

  def watcher(gameId: String, member: Member, text: String) =
    member.userId foreach { userId =>
      chat ! UserTalk(watcherId(gameId), userId, text)
    }

  private val whisperCommands = List("/whisper ", "/w ")

  def owner(gameId: String, member: Member, text: String) = (member.userId match {
    case Some(userId) =>
      whisperCommands.collectFirst {
        case command if text startsWith command =>
          UserTalk(watcherId(gameId), userId, text drop command.size)
      } orElse {
        if (text startsWith "/") none // mistyped command?
        else UserTalk(gameId, userId, text, public = false).some
      }
    case None =>
      PlayerTalk(gameId, member.color.white, text).some
  }) foreach chat.!

  private def watcherId(gameId: String) = s"$gameId/w"
} 
开发者ID:Thiediev,项目名称:lilylichessmod,代码行数:46,代码来源:Messenger.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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