Created
April 1, 2017 00:17
-
-
Save ypxu/6b9f3aabf354570d271a7ee288412d8c to your computer and use it in GitHub Desktop.
Scala PingPong 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.{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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference: http://alvinalexander.com/scala/scala-akka-actors-ping-pong-simple-example