Skip to content

Instantly share code, notes, and snippets.

@ypxu
Created April 1, 2017 00:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ypxu/6b9f3aabf354570d271a7ee288412d8c to your computer and use it in GitHub Desktop.
Save ypxu/6b9f3aabf354570d271a7ee288412d8c to your computer and use it in GitHub Desktop.
Scala PingPong Example
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
case object PingMessage
case object PongMessage
case object StartMessage
case object StopMessage
class Ping(pongRef: ActorRef) extends Actor {
var count = 0
def incrementAndPrint() = {count += 1; println("ping")}
def receive = {
case StartMessage =>
incrementAndPrint
pongRef ! PingMessage
case PongMessage =>
incrementAndPrint
if (count > 99) {
pongRef ! StopMessage
println("ping stopped")
} else {
pongRef ! PingMessage
}
}
}
class Pong extends Actor {
def receive = {
case PingMessage =>
println("Pong")
sender ! PongMessage
case StopMessage =>
println("pong stopped")
context.system.terminate()
}
}
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")
ping ! StartMessage
}
@ypxu
Copy link
Author

ypxu commented Apr 1, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment