From where we get sender actor when a particular m

2019-03-28 15:30发布

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

My question how is this 'sender' becoming accessible whenever a message is received.?

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

As far as i know, there is no way you can get ipaddress and port from where the message has come .. Is there any way by which we can obtain ipaddress of sender and port number from this 'sender' object ?

Thanks for the help.

2条回答
混吃等死
2楼-- · 2019-03-28 15:45

(You didn’t really say which actors, so I’m assuming an Akka answer is okay as well)

The sender method gives you the ActorRef which was implicitly or explicitly picked up at the sending site: if you use ! within an actor, its implicit val self: ActorRef is found and used. If that sender lives in a different ActorSystem than the recipient, i.e. it is a remote message send, then the sender ref will contain all information necessary for replying, 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 analog for port) should give you what you need.

查看更多
聊天终结者
3楼-- · 2019-03-28 15:45

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

查看更多
登录 后发表回答