Code Examples for

Actors in Scala

Return to chapter index

8 Remote Actors

  • 8.1 Creating remote actors
  • 8.2 Remote communication
  • 8.3 A remote start service
  • 8.1 Creating remote actors


    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 } } } }
    def register(name: Symbol, a: Actor): Unit

    8.2 Remote communication


    def select(node: Node, sym: Symbol): AbstractActor
    case class Node(address: String, port: Int)
    val chatRoom = select(Node("127.0.0.1", 9000), 'chatroom)
    chatRoom ! Subscribe(User("Alice")) chatRoom !? Subscribe(User("Bob")) val future = chatRoom !! Subscribe(User("Charly")) ...

    8.3 A remote start service


    case class Start(clazz: Class[_ <: Actor]) case object Stop
    class Server extends Actor { var numStarted = 0 def act() { alive(19000) register('server, this) println("remote start server running...") loop { react { case Start(clazz) => val a: Actor = clazz.newInstance() a.start() numStarted += 1 reply() case Stop => println("remote start server started " + numStarted + " remote actors") exit() } } } }
    class EchoActor extends Actor { def act() { alive(19000) register('echo, this) react { case any => reply("echo: " + any) } } }
    val server = select(Node("localhost", 19000), 'server) server !? Start(classOf[EchoActor]) val echo = select(Node("localhost", 19000), 'echo) val resp = echo !? "hello" println("remote start client received " + resp)
    remote start client received echo: hello

    For more information about Actors in Scala, please visit:

    http://www.artima.com/shop/actors_in_scala

    and:

    http://booksites.artima.com/actors_in_scala

    Copyright © 2011 Artima, Inc. All rights reserved.

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.