6

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.

user1822249
  • 727
  • 2
  • 8
  • 12

2 Answers2

6

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

Roland Kuhn
  • 15,412
  • 2
  • 36
  • 45
  • 1
    Unfortunately I am not using akka ... Do you know how this can be done in scala actors ?... Thanks for the help anyway ... – user1822249 Nov 15 '12 at 16:33
  • 3
    I have never used remoting with scala.actors, but from what I hear you might be interested in looking into Akka, it is an industry-proven solution. scala.actors.remote has not been touched since July 2009 (not counting general scala library refactoring), so I think it is fair to say that it is unmaintained. – Roland Kuhn Nov 15 '12 at 17:17
1

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.