Scala – How to get the absolute remote actor url from inside the actor

akkascala

I want to do do something like this .

Actor A :

    actorB ! "info"

     def receive()={
     case _ => {
          println("Remote address is "+ _)

        }
}

Actor B : (this deployed remotely )

def receive()={
 case "info" => {
      sender tell self.path.address.toString

    }

}

I want it to return me the string akka://10.4.20.40:2555/slave/user/slaverunner . But what I get is just akka://slave. How do I get the remote host and port? . The properties host,port and hostport on the address object dont return anything

Best Answer

If you call

sender.path.toString

in actor A you will get the address of the sender. So you don't need to pass the address to another actor system as long as you can send a message to it.

Akka will not give you a remote path for an actor in the local system, which is why self.path.address.toString in actor B won't work.

If you really want to send the host and port from B to A then you'll need to get access to a RemoteActorRefProvider via the ExtendedActorSystem. The official way to do that is through an Extension. For example:

class MyExtensionImpl(system: ExtendedActorSystem) extends Extension {
  def address = system.provider match {
    case rarp: RemoteActorRefProvider => rarp.transport.address
    case _ => system.provider.rootPath.address
  }
}

object MyExtension extends ExtensionKey[MyExtensionImpl]

val address = MyExtension(system).address

And that will give you the exact address that you need to communicate remotely with B.

(note this code works with Akka 2.0.x. In 2.1.x you can avoid going through RemoteActorRefProvider by using system.provider.getDefaultAddress)

In Akka if you are using constructing actor addresses this way for use with actorFor then you need to make sure the hostnames match exactly.

For example if the ActorSystem thinks the host is foo.bar.com, then it will ignore the messages sent by a remote host to actorFor("akka://slave@foo:2555/user/slaverunner")

Related Topic