blog:scala_distributed_ping_pong

no way to compare when less than two revisions

Differences

This shows you the differences between two versions of the page.


blog:scala_distributed_ping_pong [2009/11/27 17:54] (current) – created - external edit 127.0.0.1
Line 1: Line 1:
 +====== Scala distributed ping pong ======
 +
 +This small scala example demonstrates the simplicity in which distributed programming is possible using the actor model.  We setup an ECHOSERVER that simply responds with a PONG to any PING request it receives and we run this on an arbitrary server.
 +
 +<code scala>
 +/*
 + * EchoServer.scala
 + */
 +
 +package echoapp
 +
 +import scala.actors.Actor._
 +import scala.actors.remote.{Locator,Node,RemoteActor}
 +import scala.actors.remote.RemoteActor.{alive,register}
 +
 +class Server(me : Locator) {
 +    RemoteActor.classLoader = getClass().getClassLoader()
 +    actor {
 +        alive(me.node.port)
 +        register(me.name, self)
 +        loop {
 +            react {
 +                case 'PING => reply("PONG") // equiv:  sender ! "PONG"
 +                case msg => println(msg)
 +            }
 +        }
 +    }
 +}
 +
 +object EchoServer  {
 +    def main(args: Array[String]) {
 +        val me = new Locator(Node("127.0.0.1", 9010), 'echoServer)
 +        new Server(me)
 +        println("Echo server started")
 +    }
 +}
 +</code>
 +
 +For the sake of brevity the IP address of where the ECHOSERVER is running has been hardcoded.  The client sends a PING message to the remote echo server and gathers the response(s).
 +
 +<code scala>
 +/*
 + * EchoClient.scala
 + */
 +
 +package echoapp
 +
 +import scala.actors.Actor._
 +import scala.actors.remote.{Locator,Node,RemoteActor}
 +import scala.actors.remote.RemoteActor._
 +
 +class Client(servloc : Locator) {
 +    RemoteActor.classLoader = getClass().getClassLoader()
 +    val server = select(servloc.node, servloc.name)
 +    actor {
 +        // The response is sent back to the thread that did the send.
 +        // If we move to this to main() then this is where the reponse will go
 +        // as we have no react/receive there it will be lost.
 +        server ! 'PING
 +        loop {
 +            react {
 +                case msg => 
 +                    println(msg)
 +            }
 +        }
 +    }    
 +}
 +
 +object EchoClient {
 +    def main(args: Array[String]) {
 +        val echoServer = Locator(Node("192.168.1.13", 9010), 'echoServer)
 +        new Client(echoServer)
 +    }
 +}
 +</code>
 +
 +{{tag>scala programming}}
  
  • blog/scala_distributed_ping_pong.txt
  • Last modified: 2009/11/27 17:54
  • by 127.0.0.1