Keeping references to two actors

心不动则不痛 提交于 2019-12-25 02:06:34

问题


I am making a little 2 player game that will work over the network with actors. Each client sends a message to the server to join and I want to keep references to the senders at that point, but when the second player joins it overwrites my reference to the first one:

case class JoinMsg

class Server(port: Int) extends Actor {
  var client1: OutputChannel[Any] = null
  var client2: OutputChannel[Any] = null
  def act() {
    alive(port)
    register('Server, self)
    while (true) {
      receive {
        case JoinMsg =>
          if (client1 == null) {
            Console.println("got player 1")
            client1 = sender
            client1 ! new Msg("Waiting for player 2")
          } else if (client2 == null) {
            Console.println("got player 2")
            client2 = sender
            Console.println("blatted client1?: "+(client1 == client2))//true
            client1 ! new Msg("hi")
            client2 ! new Msg("hi")
          }
      }
    }
  }
}

What's the right way to go about this? Thx.


回答1:


With Akka it would look like this:

import akka.actor._

case object JoinMsg
case class Msg(s: String)

class Server extends Actor {

  def receive = {
    case JoinMsg =>
      println("got player 1")
      sender ! Msg("Waiting for player 2")
      context.become(waitingForPlayer2(sender))
  }

  def waitingForPlayer2(client1: ActorRef): Actor.Receive = {
    case JoinMsg =>
      println("got player 2")
      sender ! Msg("hi")
      client1 ! Msg("hi")
      context.become(ready(client1, sender))
  }

  def ready(client1: ActorRef, client2: ActorRef): Actor.Receive = {
    case m: Msg if sender == client1 => client2 ! m
    case m: Msg if sender == client2 => client1 ! m
  }
}

object Demo extends App {
  val system = ActorSystem("Game")
  val server = system.actorOf(Props[Server], "server")

  system.actorOf(Props(new Actor {
    server ! JoinMsg
    def receive = {
      case Msg(s) => println(s)
    }
  }))

  system.actorOf(Props(new Actor {
    server ! JoinMsg
    def receive = {
      case Msg(s) => println(s)
    }
  }))
}

Exact same actor code can be used with remote actors. You only need a few lines of configuration and the lookup of the server from the clients is performed with actorFor. Read about Akka remote actors.



来源:https://stackoverflow.com/questions/15527193/keeping-references-to-two-actors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!