-
-
Save daviscale/a10aa5f03a95cea61bad to your computer and use it in GitHub Desktop.
PingPong Akka intro example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import akka.actor._ | |
/** The messages that the Ping actor responds to */ | |
object PingProtocol { | |
case object StartMessage | |
case object PongMessage | |
} | |
/** The messages that the Pong actor responds to */ | |
object PongProtocol { | |
case object PingMessage | |
case object StopMessage | |
} | |
/** | |
* An Akka Actor example written by Alvin Alexander of | |
* http://devdaily.com | |
* | |
* Shared here under the terms of the Creative Commons | |
* Attribution Share-Alike License: http://creativecommons.org/licenses/by-sa/2.5/ | |
* | |
* more akka info: http://doc.akka.io/docs/akka/snapshot/scala/actors.html | |
*/ | |
class Ping(pong: ActorRef) extends Actor { | |
import PingProtocol._ | |
import PongProtocol._ | |
var count = 0 | |
def incrementAndPrint { count += 1; println("ping - Thread %s:".format(Thread.currentThread.getName)) } | |
def receive = { | |
case StartMessage => | |
incrementAndPrint | |
pong ! PingMessage | |
case PongMessage => | |
incrementAndPrint | |
if (count > 99) { | |
sender ! StopMessage | |
println("ping stopped") | |
context.stop(self) | |
} else { | |
sender ! PingMessage | |
} | |
} | |
} | |
class Pong extends Actor { | |
import PingProtocol._ | |
import PongProtocol._ | |
def receive = { | |
case PingMessage => | |
println(" pong - Thread %s:".format(Thread.currentThread.getName)) | |
sender ! PongMessage | |
case StopMessage => | |
println("pong stopped") | |
context.stop(self) | |
} | |
} | |
object PingPongTest extends App { | |
val system = ActorSystem("PingPongSystem") | |
val pong = system.actorOf(Props[Pong], name = "pong") | |
val ping = system.actorOf(Props(new Ping(pong)), name = "ping") | |
// start them going | |
ping ! PingProtocol.StartMessage | |
// shutdown - important to call this from the REPL so that the REPL can be closed cleanly | |
system.shutdown | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment