import scala.actors.Actor import Actor._ import scala.actors.remote.RemoteActor.{alive, register}
class ChatRoom extends Actor { def act() { alive(9000) register('chatroom, self) loop { receive { case Subscribe(user) => // handle subscriptions case Unsubscribe(user) => // handle unsubscriptions case UserPost(user, post) => // handle user posts } } } }
Listing 8.1 shows how to turn the chat room actor into a remote actor. First, the actor runtime system needs to be informed that the actor wants to engage in remote communication with other actors. You do this by invoking the alive method of the RemoteActor object. It requires specifying a port number that is used to listen for incoming Transmission Control Protocol (TCP) connections. Actors running on different machines in the network use this port number to obtain a remote reference to the chat room actor.
The port number is not enough to uniquely identify the actor, however; several remote actors may be accessible via the same port. Therefore, remote actors must be registered under a name that is unique for a given port number by using the register method of RemoteActor:
def register(name: Symbol, a: Actor): Unit
The method expects two arguments: The first argument is the name under which the actor should be registered. The second argument is the actor that should be registered; in the example in Listing 8.1, it is simply self. Subsequently, you can obtain a remote reference to the chat room actor using the port number, the IP address of the machine on which the actor is running, and the name under which it is registered on that machine.
Note that you can change the name under which an actor is registered by repeatedly invoking register, passing different symbols. However, at any point in time an actor is registered under a single name only. The most recent invocation of register "wins."
To communicate with the chat room, messages must be serialized and sent over the network. Therefore, the message classes need to be serializable. Fortunately, the message classes defined in Listing 4.1 are all case classes, which are serializable by default.