From where we get sender actor when a particular message is received?

三世轮回 提交于 2020-01-01 05:25:05

问题


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.


回答1:


(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.




回答2:


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.



来源:https://stackoverflow.com/questions/13370277/from-where-we-get-sender-actor-when-a-particular-message-is-received

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!