我想异步地从客户端的Actor发送消息(!)并从服务器向Actor返回一条消息。关键是我不想使用(?)并获得未来。
我有以下示例代码:
import akka.actor.Actor._
import akka.event.EventHandler
import akka.actor.{ActorRef, Actor}
case class FromUser(s: String)
case class FromServer(s: String)
class ServerActor extends Actor {
protected def receive = {
case FromUser(msg) => self.sender ! FromServer(msg)
}
}
class ClientActor(val remoteServer: ActorRef) extends Actor {
protected def receive = {
case FromUser(msg) => {
EventHandler.info(this, "I got '" + msg + "' from the user.")
remoteServer ! FromUser(msg)
}
case FromServer(msg) => EventHandler.info(this, "I got '" + msg + "' from the server.")
}
}
object Client {
def main(args: Array[String]) {
val s = Actor.remote.actorFor("ServerActor", "NYCWD2328", 4552)
val c = Actor.actorOf(new ClientActor(s)).start
c ! FromUser("Hello")
}
}
object Server {
def main(args: Array[String]) {
Actor.remote.start("NYCWD2328", 4552)
Actor.remote.register("ServerActor", actorOf(new ServerActor))
}
}
此代码失败,并显示以下跟踪:
[GENERIC] [11/9/11 12:32 PM] [RemoteClientWriteFailed(uuid {
high: 15711794799146701281
low: 10512246108465469656
}
actorInfo {
....
timeout: 5000
}
,java.nio.channels.ClosedChannelException,akka.remote.netty.NettyRemoteSupport@a1d1f4,/127.0.0.1:2552)]
[GENERIC] [11/9/11 12:32 PM] [RemoteClientError(java.nio.channels.ClosedChannelException,akka.remote.netty.NettyRemoteSupport@a1d1f4,/127.0.0.1:2552)]
[ERROR] [11/9/11 12:32 PM] [akka:event-driven:dispatcher:global-3] [LocalActorRef] null
java.nio.channels.ClosedChannelException
at org.jboss.netty.channel.socket.nio.NioWorker.cleanUpWriteBuffer(NioWorker.java:643)
这似乎应该可行。是吗?
答案 0 :(得分:0)
这是一个老问题,Viktor已经回答了,但我不喜欢“无应答”状态,所以为了完整性:主要方法应改为
object Client {
def main(args: Array[String]) {
// choose available port on local machine
Actor.remote.start("YourHostnameHere", 4553)
val s = Actor.remote.actorFor("ServerActor", "NYCWD2328", 4552)
val c = Actor.actorOf(new ClientActor(s)).start
c ! FromUser("Hello")
}
}
必须可以从远程计算机(此处为“NYCWD2328”)访问已启动的远程服务(主机和端口),因为将通过该远程主机启动的新连接发送回复。