我正在制作一个可以通过网络与演员合作的小玩家游戏。每个客户端都向服务器发送一条消息进行加入,我希望在那时继续引用发送者,但是当第二个玩家加入它时会覆盖我对第一个引用的引用:
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")
}
}
}
}
}
正确的方法是什么? THX。
答案 0 :(得分:1)
对于Akka,它看起来像这样:
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)
}
}))
}
完全相同的actor代码可以与远程actor一起使用。您只需要几行配置,并且使用actorFor
从客户端查找服务器。阅读Akka remote actors。