Where do we get the sending agent when a particular message is received?

Whenever an actor receives a message in scala, we can access the sender of the actor using the keyword 'sender', which is the object of the AbstractActor trait.

My question is: how does this 'sender' become available whenever a message is received?

and we can also redefine this implementation, where along with the sender other data is also available, such as ipaddress, the port where the data came from.

As far as I know, you cannot get ipaddress and the port where the message came from. Is there any way by which we can get the sender ipaddress and port number from this 'sender' object?

Thanks for the help.

+6
source share
2 answers

(You really didn’t say which actors, so I guess Akka’s answer is ok too)

The sender method gives you an ActorRef that was implicitly or explicitly selected on the sending site: if you use ! inside an actor, its implicit val self: ActorRef found and used. If this sender lives in a different ActorSystem than the receiver, i.e. It sends a remote message, then sender ref will contain all the information needed to respond, just look at its path:

 val s = sender // Actor[akka://<system>@<host>:<port>/user/path/to/actor] val p = s.path // akka://<system>@<host>:<port>/user/path/to/actor val a = p.address // akka://<system>@<host>:<port> val host = a.host // Some(<host>), where <host> is the listen address as configured for the remote system val port = a.port // Some(<port>), where <port> is the actual listen port of the remote system 

So, in short, sender.path.address.host (and the equivalent for the port) should provide you with what you need.

+5
source

In the AKKA acting system ,! overloaded as def (message: scala.Any) (implicit sender: akka.actor.ActorRef) where the sender is the actor who sent the message. After that, you can call the path method on ActorRef, but I don’t think you can get the real IP address from there.

+1
source

All Articles