我正在尝试Akka远程演员,试图建立一个简单的2人游戏在网络上。This answer到一个较早的问题给了我一个很好的起点,但现在我有一个很难理解如何适应我的情况。ISTM,原来是连接两次从同一客户端我想做的是从不同的客户端运行它两次,但是当我这样做的时候,我会得到一个BindException,地址已被使用。我猜这是因为每次我运行代码时,它都试图启动服务器?我需要一个可以独立于客户端的连接和断开来启动和停止主角色的环境。(最小的)Akka配置和异常在代码后面:
import akka.actor._
//example from answer to https://stackoverflow.com/questions/15527193/keeping-references-to-two-actors
// by Patrick Nordwall
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
}
}
/* I want to run this once for each "player" */
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)
}
}))
/* Rather than connecting twice from the same node, I want to run this
program twice from different nodes
system.actorOf(Props(new Actor {
server ! JoinMsg
def receive = {
case Msg(s) => println(s)
}
}))*/
}
设定:
akka {
actor {
provider = "akka.remote.RemoteActorRefProvider"
}
remote {
transport = "akka.remote.netty.NettyRemoteTransport"
netty {
hostname = "localhost"
port = 9000
}
}
}
例外情况:
Exception in thread "main" java.lang.ExceptionInInitializerError
at akkademo.main(akkademo.scala)
Caused by: org.jboss.netty.channel.ChannelException: Failed to bind to: localhost/127.0.0.1:9000
at org.jboss.netty.bootstrap.ServerBootstrap.bind(ServerBootstrap.java:298)
at akka.remote.netty.NettyRemoteServer.start(Server.scala:54)
at akka.remote.netty.NettyRemoteTransport.start(NettyRemoteSupport.scala:90)
at akka.remote.RemoteActorRefProvider.init(RemoteActorRefProvider.scala:94)
at akka.actor.ActorSystemImpl._start(ActorSystem.scala:588)
at akka.actor.ActorSystemImpl.start(ActorSystem.scala:595)
at akka.actor.ActorSystem$.apply(ActorSystem.scala:111)
at akka.actor.ActorSystem$.apply(ActorSystem.scala:93)
at akkademo$.<init>(akkademo.scala:4)
at akkademo$.<clinit>(akkademo.scala)
... 1 more
Caused by: java.net.BindException: Address already in use
短暂性脑缺血发作
3条答案
按热度按时间nkcskrwz1#
在同一台计算机上运行多个示例时,需要为它们配置不同的端口。在本例中,只有服务器需要已知端口(9000)。对于客户端,可以使用0作为随机可用端口。
为客户端定义另一个配置文件。
client.conf
:使用以下配置在客户端中启动
ActorSystem
:在客户端中,您将使用以下内容查找服务器:
pb3skfrl2#
您需要单独指定客户端配置的端口,或者将服务器端配置的端口从2552更改为其他端口。2552是akka actor系统的默认端口,当您在客户端创建actor系统以进行查找(在同一台机器上)时,如果未显式指定端口2552,它也会尝试绑定到端口2552,因此您会收到此错误。
jdgnovmf3#
另一种更简单的方法是关闭所有终端窗口并打开新窗口。即使在停止所有节点后仍面临同样的问题,但将在同一终端中运行,而不是打开新窗口